dsh-ris-ide 1.7.3 → 1.8.1

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.
Files changed (75) hide show
  1. package/README.md +21 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +284 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +609 -1178
  6. package/lib/index.js +1124 -55
  7. package/lib/janitor.js +106 -15
  8. package/lib/proxy.js +86 -7
  9. package/lib/proxybridge-bundle.js +798 -0
  10. package/lib/proxybridge-health.js +206 -0
  11. package/lib/redirector.js +1615 -115
  12. package/lib/risd/build.js +91 -0
  13. package/lib/risd/debug.js +374 -0
  14. package/lib/risd/git.js +207 -0
  15. package/lib/risd/leases.js +124 -0
  16. package/lib/risd/lifecycle.js +148 -0
  17. package/lib/risd/log.js +59 -0
  18. package/lib/risd/ping.js +94 -0
  19. package/lib/risd/programs.js +348 -0
  20. package/lib/risd/server.js +1919 -0
  21. package/lib/risd/state.js +137 -0
  22. package/lib/risd/ui.js +1989 -0
  23. package/lib/risd/view.js +79 -0
  24. package/lib/risd-client.js +282 -0
  25. package/lib/standalone/window.html +14 -16
  26. package/lib/startup.js +114 -0
  27. package/package.json +4 -1
  28. package/test/client-build.test.mjs +113 -0
  29. package/test/client-viewer.test.mjs +279 -227
  30. package/test/dsh-origin.test.mjs +140 -0
  31. package/test/dsh-window-refresh.test.mjs +100 -0
  32. package/test/harness.test.mjs +9 -0
  33. package/test/host-noloop.test.mjs +74 -0
  34. package/test/host-tail.test.mjs +21 -4
  35. package/test/host-window.test.mjs +4 -4
  36. package/test/janitor.test.mjs +29 -1
  37. package/test/lifecycle.test.mjs +26 -5
  38. package/test/merge-owners.test.mjs +155 -0
  39. package/test/proxy-restart.test.mjs +39 -0
  40. package/test/proxy-window.test.mjs +45 -0
  41. package/test/proxy.test.mjs +41 -0
  42. package/test/proxybridge-bundle.test.mjs +687 -0
  43. package/test/proxybridge-health.test.mjs +116 -0
  44. package/test/redirector-bundle.test.mjs +391 -0
  45. package/test/redirector.test.mjs +413 -10
  46. package/test/risd-api.test.mjs +514 -0
  47. package/test/risd-bridge-degrade.test.mjs +101 -0
  48. package/test/risd-build.test.mjs +20 -0
  49. package/test/risd-cli-home.test.mjs +50 -0
  50. package/test/risd-client.test.mjs +130 -0
  51. package/test/risd-debug.test.mjs +261 -0
  52. package/test/risd-election.test.mjs +104 -0
  53. package/test/risd-engine.test.mjs +132 -0
  54. package/test/risd-entry.test.mjs +118 -0
  55. package/test/risd-git.test.mjs +109 -0
  56. package/test/risd-handoff.test.mjs +116 -0
  57. package/test/risd-heal.test.mjs +50 -0
  58. package/test/risd-helpers.mjs +108 -0
  59. package/test/risd-host-p2.test.mjs +147 -0
  60. package/test/risd-janitor-guard.test.mjs +46 -0
  61. package/test/risd-lease.test.mjs +83 -0
  62. package/test/risd-lifecycle.test.mjs +210 -0
  63. package/test/risd-log-follow.test.mjs +227 -0
  64. package/test/risd-mode.test.mjs +161 -0
  65. package/test/risd-ping.test.mjs +99 -0
  66. package/test/risd-programs.test.mjs +169 -0
  67. package/test/risd-restart.test.mjs +104 -0
  68. package/test/risd-review-p2.test.mjs +217 -0
  69. package/test/risd-shutdown.test.mjs +97 -0
  70. package/test/risd-teardown.test.mjs +87 -0
  71. package/test/risd-tools.test.mjs +211 -0
  72. package/test/risd-ui.test.mjs +607 -0
  73. package/test/risd-write.test.mjs +170 -0
  74. package/test/startup-reconcile.test.mjs +100 -0
  75. package/test/windows.test.mjs +37 -2
package/lib/risd/ui.js ADDED
@@ -0,0 +1,1989 @@
1
+ // The daemon's own maintenance page (Phase 3-lite, triggered by a real gap):
2
+ // when no dsh is open there is no panel, yet the daemon may still own a proxy
3
+ // engine, running programs (JVMs) and a debug session. Those must be stoppable.
4
+ //
5
+ // Phase 2-lite follow-up: the page now has three top tabs —
6
+ // 概览 · proxy state + running programs grouped by workspace + debug sessions
7
+ // 代理 · the machine-wide rule table (independent of dsh: CAS save via /v1/proxy,
8
+ // engine start/stop, bridge restart, proxy log tail)
9
+ // IDE · embeds the dsh IDE window when a dsh window is answering, greyed out
10
+ // with the reason otherwise (GET /v1/dsh reads dsh-window.json)
11
+ //
12
+ // One self-contained HTML file: no DSH client bundle, no npm dependency, no build
13
+ // step. It is served only to loopback requests (Host check) and carries the token
14
+ // inline — anyone able to load it can already read `risd.json` anyway.
15
+
16
+ /** Escape text for the inline `<script>` token assignment. */
17
+ function jsonForScript(value) {
18
+ return JSON.stringify(value).replace(/</g, '\\u003c')
19
+ }
20
+
21
+ /**
22
+ * Render the maintenance page.
23
+ * @param options - `{ token, version, home, apiVersion }`.
24
+ * @returns the HTML document.
25
+ */
26
+ export function risdUiHtml(options) {
27
+ const token = jsonForScript(options.token ?? '')
28
+ const version = jsonForScript(options.version ?? '')
29
+ const home = jsonForScript(options.home ?? '')
30
+ const apiVersion = jsonForScript(String(options.apiVersion ?? '1'))
31
+ // The code THIS process runs (see risd/build.js): the page compares it with what
32
+ // /v1/health reports and offers a refresh once a restarted daemon has new code.
33
+ const uiBuild = jsonForScript(String(options.uiBuild?.loaded ?? ''))
34
+ // Which daemon PROCESS rendered this page. A restart may keep the same code but
35
+ // issue a new token: the old page then answers 401 to everything, and comparing
36
+ // this value with /v1/health's `instance` is how the page notices (review C3-P1-3).
37
+ const uiInstance = jsonForScript(String(options.uiInstance ?? ''))
38
+ return `<!doctype html>
39
+ <html lang="zh-CN">
40
+ <head>
41
+ <meta charset="utf-8">
42
+ <meta name="viewport" content="width=device-width, initial-scale=1">
43
+ <title>risd — 本机代理与程序维护</title>
44
+ <style>
45
+ :root { color-scheme: light; --b:#e4e7ec; --muted:#6b7280; --bg:#f7f8fa; --card:#fff; --accent:#2f7cf6; --danger:#dc2626; --ok:#15803d; }
46
+ * { box-sizing: border-box; }
47
+ body { margin:0; background:#fff; font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"PingFang SC","Microsoft YaHei",sans-serif; color:#111; }
48
+ header { display:flex; align-items:center; gap:14px; padding:12px 24px; background:var(--card); border-bottom:1px solid var(--b); position:sticky; top:0; z-index:5; }
49
+ header h1 { position:relative; z-index:1; font-size:15px; margin:0 0 0 6px; font-weight:650; letter-spacing:.2px; }
50
+ .side-toggle { width:26px; height:26px; flex:0 0 26px; display:flex; align-items:center; justify-content:center;
51
+ border:0; border-radius:6px; background:transparent; color:var(--muted); font-size:16px; line-height:1; cursor:pointer; }
52
+ .side-toggle:hover { background:#f1f3f6; color:#111; }
53
+ .side-toggle:disabled { opacity:.35; cursor:default; }
54
+ .side-toggle:disabled:hover { background:transparent; color:var(--muted); }
55
+ header .meta { color:var(--muted); font-size:12px; }
56
+ header .spacer { flex:1; }
57
+ nav { position:absolute; left:50%; transform:translateX(-50%); display:flex; gap:4px; }
58
+ nav button { font:inherit; font-size:13px; padding:5px 14px; border:1px solid transparent; border-radius:7px; background:transparent; color:var(--muted); cursor:pointer; }
59
+ nav button:hover { background:#f1f3f6; color:#111; }
60
+ nav button[aria-selected="true"] { background:#eef4ff; border-color:#d7e4ff; color:var(--accent); font-weight:600; }
61
+ nav button:disabled { opacity:.4; cursor:not-allowed; }
62
+ nav button:disabled:hover { background:transparent; color:var(--muted); }
63
+ main { padding:0; }
64
+ .view#view-overview, .view#view-proxy { max-width:1120px; margin:0 auto; padding:18px 24px 60px; display:flex; flex-direction:column; gap:14px; }
65
+ .view#view-ide { height:calc(100vh - 53px); }
66
+ .ide-stale { display:flex; align-items:center; gap:8px; padding:6px 12px; background:#fff8e6; border-bottom:1px solid #f0d8a8; color:#8a5a00; font-size:12px; }
67
+ .ide-stale[hidden] { display:none; }
68
+ /* 「页面代码变了但 daemon 还是旧模块」提示:纯静态页面本身没有热更新,daemon
69
+ import 过的模块也不会再读盘,只能重启 daemon;这条横幅把「为什么刷新没用」
70
+ 说出来,而不是让用户反复强刷。 */
71
+ #bridge-health-more { font-size:13px; }
72
+ #bridge-health-more summary { color:var(--muted); cursor:pointer; }
73
+ #bridge-health-detail { font-size:13px; line-height:1.5; }
74
+ .ui-drift { display:flex; align-items:center; gap:8px; padding:6px 12px; background:#eef4ff; border-bottom:1px solid #d7e4ff; color:#1d4ed8; font-size:12px; }
75
+ .ui-drift[hidden] { display:none; }
76
+ .ui-drift span { flex:1; }
77
+ .ui-drift button { border:0; background:transparent; color:inherit; font:inherit; cursor:pointer; padding:0 4px; }
78
+ .ui-drift #ui-drift-save { border:1px solid #bcd3ff; background:#fff; border-radius:6px; padding:2px 10px; }
79
+ .ui-drift #ui-drift-save:disabled { opacity:.5; cursor:default; }
80
+ .ui-drift #ui-drift-save[hidden] { display:none; }
81
+ .ui-drift #ui-drift-reload { border:1px solid #bcd3ff; background:#fff; border-radius:6px; padding:2px 10px; }
82
+ .ide-stale span { flex:1; }
83
+ .ide-stale button { border:0; background:transparent; color:#8a5a00; font-size:15px; line-height:1; padding:0 2px; cursor:pointer; }
84
+ .ide-stale button:hover { color:#5c3c00; }
85
+ .view[hidden] { display:none !important; }
86
+ section { background:var(--card); border:1px solid var(--b); border-radius:10px; padding:14px 18px; }
87
+ section h2 { margin:0 0 10px; font-size:13px; font-weight:650; display:flex; align-items:center; gap:8px; }
88
+ section h2 .sub { color:var(--muted); font-weight:400; font-size:12px; }
89
+ .row { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
90
+ .grow { flex:1; }
91
+ button { font:inherit; padding:5px 12px; border-radius:6px; border:1px solid var(--b); background:#fff; cursor:pointer; }
92
+ button:hover { border-color:#c9ced6; }
93
+ button.primary { background:var(--accent); border-color:var(--accent); color:#fff; }
94
+ button.danger { color:var(--danger); border-color:#f3c7c7; }
95
+ button:disabled { opacity:.45; cursor:default; }
96
+ /* Long operations (sudo/UAC behind start) keep the button visibly busy instead of
97
+ looking dead; the label says which half is running. */
98
+ button[aria-busy="true"] { opacity:.7; cursor:progress; }
99
+ input, select { font:inherit; padding:5px 8px; border:1px solid var(--b); border-radius:6px; background:#fff; }
100
+ input.narrow { width:110px; }
101
+ table { width:100%; border-collapse:collapse; font-size:13px; }
102
+ th, td { text-align:left; padding:6px 8px; border-bottom:1px solid #f0f1f4; vertical-align:middle; }
103
+ th { color:var(--muted); font-weight:500; font-size:12px; }
104
+ td input[type="text"] { width:100%; }
105
+ td.actions { white-space:nowrap; text-align:right; }
106
+ .pill { display:inline-block; padding:1px 8px; border-radius:999px; font-size:11px; border:1px solid var(--b); color:var(--muted); }
107
+ .pill.on { color:var(--ok); border-color:#bbe3c8; background:#f0fdf4; }
108
+ .pill.off { color:var(--muted); }
109
+ .pill.warn { color:#b45309; border-color:#fde3b3; background:#fffbeb; }
110
+ /* SOCKS reachability chip: quiet while probing, green when the greeting answered,
111
+ amber when the host answered but is not a usable SOCKS5. */
112
+ #proxy-ping.busy { color:var(--muted); }
113
+ #proxy-ping.on { color:var(--ok); border-color:#bbe3c8; background:#f0fdf4; }
114
+ #proxy-ping.warn { color:#b45309; border-color:#fde3b3; background:#fffbeb; }
115
+ #proxy-ping.err { color:#b91c1c; border-color:#fecaca; background:#fef2f2; }
116
+ #bridge-pill.on { color:var(--ok); border-color:#bbe3c8; background:#f0fdf4; }
117
+ #bridge-pill.warn { color:#b45309; border-color:#fde3b3; background:#fffbeb; }
118
+ #bridge-pill.err { color:#b91c1c; border-color:#fecaca; background:#fef2f2; }
119
+ .muted { color:var(--muted); }
120
+ .empty { color:var(--muted); padding:6px 0; }
121
+ pre { margin:8px 0 0; background:#0f172a; color:#d6deeb; padding:10px 12px; border-radius:8px; max-height:340px; overflow:auto; font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; white-space:pre-wrap; word-break:break-all; }
122
+ ol.sessions, ul.programs { list-style:none; margin:0; padding:0; }
123
+ ul.programs li, ol.sessions li { display:flex; align-items:center; gap:10px; padding:6px 0; border-bottom:1px solid #f0f1f4; }
124
+ ul.programs li:last-child, ol.sessions li:last-child { border-bottom:0; }
125
+ .group-title { font-weight:600; font-size:12px; color:#374151; margin:10px 0 2px; }
126
+ .ide-layout { display:flex; height:100%; min-height:0; }
127
+ .ide-side { flex:0 0 208px; width:208px; border-right:1px solid var(--b); display:flex; flex-direction:column; min-height:0; background:#fbfbfc; }
128
+ .ide-side[hidden] { display:none; }
129
+ .ide-side ul { list-style:none; margin:0; padding:6px; overflow:auto; flex:1; }
130
+ .ide-side li button { width:100%; text-align:left; border:0; background:transparent; padding:6px 8px; border-radius:6px; font-size:12.5px; font-weight:400; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; color:#111; }
131
+ .ide-side li button:hover { background:#f1f3f6; }
132
+ .ide-side li button.active { background:#eef4ff; color:var(--accent); font-weight:600; }
133
+ .ide-side .note { padding:0 14px 10px; }
134
+ .ide-main { flex:1; min-width:0; display:flex; flex-direction:column; min-height:0; }
135
+ .ide-body { flex:1; min-height:0; display:flex; flex-direction:column; }
136
+ .ide-body .ide-frame { flex:1; width:100%; height:100%; border:0; border-radius:0; }
137
+ .ide-body .ide-frame[hidden] { display:none; }
138
+ .ide-body .ide-msg { flex:1; min-height:0; overflow:auto; }
139
+ .ide-body .empty, .ide-body .banner { margin:18px; }
140
+
141
+ .ide-frame { width:100%; height:70vh; border:1px solid var(--b); border-radius:8px; background:#fff; }
142
+ .note { font-size:12px; color:var(--muted); }
143
+ .life { display:flex; align-items:center; gap:10px; padding:6px 0; font-size:13px; }
144
+ .life b { min-width:96px; font-weight:600; }
145
+ .life input { margin:0; }
146
+ .modal { position:fixed; inset:0; display:flex; align-items:center; justify-content:center; background:rgba(17,24,39,.45); z-index:50; }
147
+ .modal[hidden] { display:none; }
148
+ .modal-card { width:440px; max-width:calc(100% - 32px); background:#fff; border-radius:12px; padding:20px 22px; box-shadow:0 24px 48px rgba(17,24,39,.22); }
149
+ .modal-card h3 { margin:0 0 10px; font-size:16px; }
150
+ .modal-card .modal-body { font-size:13px; color:#374151; line-height:1.7; }
151
+ .modal-card .modal-body b { color:#111827; }
152
+ .modal-card .modal-actions { display:flex; justify-content:flex-end; gap:8px; margin-top:18px; }
153
+ .banner { padding:8px 12px; border-radius:8px; font-size:13px; }
154
+ /* An empty banner wrapper is still a flex item, so the 14px gap counted it and
155
+ pushed 概览 content down one gap lower than 代理设置 (m11445). Hidden when empty. */
156
+ #overview-banner:empty, #proxy-banner:empty { display:none; }
157
+ .banner.warn { background:#fffbeb; border:1px solid #fde3b3; color:#92400e; }
158
+ .banner.ok { background:#f0fdf4; border:1px solid #bbe3c8; color:#166534; }
159
+ .banner.err { background:#fef2f2; border:1px solid #fecaca; color:#991b1b; }
160
+ </style>
161
+ </head>
162
+ <body>
163
+ <header>
164
+ <button type="button" id="ide-side-toggle" class="side-toggle" title="展开工作区面板" aria-label="展开工作区面板" aria-expanded="false">›</button>
165
+ <h1>risd</h1>
166
+ <span class="spacer"></span>
167
+ <nav role="tablist" aria-label="维护页">
168
+ <button role="tab" data-tab="ide" aria-selected="false">开发环境</button>
169
+ <button role="tab" data-tab="proxy" aria-selected="false">代理设置</button>
170
+ <button role="tab" data-tab="overview" aria-selected="true">概览</button>
171
+ </nav>
172
+ </header>
173
+ <div id="ui-drift" class="ui-drift" hidden>
174
+ <span id="ui-drift-text">插件版本已更新:点「重启并刷新」后生效。</span>
175
+ <button type="button" id="ui-drift-save" title="保存开发环境里所有未保存的文件" hidden>保存所有文件</button>
176
+ <button type="button" id="ui-drift-reload" title="重新加载本页">刷新</button>
177
+ <button type="button" id="ui-drift-close" title="关闭提示" aria-label="关闭提示">×</button>
178
+ </div>
179
+ <main>
180
+ <div class="view" id="view-overview">
181
+ <div id="overview-banner"></div>
182
+ <section>
183
+ <h2>守护进程 <span class="sub" id="daemon-sub"></span></h2>
184
+ <div class="row">
185
+ <span class="pill" id="daemon-pill">未知</span>
186
+ <span class="muted" id="daemon-detail"></span>
187
+ <span class="grow"></span>
188
+ <button class="danger" id="daemon-stop">停止</button>
189
+ </div>
190
+ </section>
191
+ <section>
192
+ <h2>代理运行状态 <span class="sub" id="proxy-sub"></span></h2>
193
+ <div class="row">
194
+ <span class="pill" id="proxy-pill">未知</span>
195
+ <span class="muted" id="proxy-detail"></span>
196
+ <span class="grow"></span>
197
+ <button id="engine-toggle" disabled>启动</button>
198
+ </div>
199
+ </section>
200
+ <section>
201
+ <h2>运行中的项目 <span class="sub">按工作区分组;只有运行中的才会出现</span></h2>
202
+ <div id="projects"><p class="empty">加载中…</p></div>
203
+ </section>
204
+ <section>
205
+ <h2>调试中的进程 <span class="sub">JDWP 会话由 daemon 持有</span></h2>
206
+ <div id="debugs"><p class="empty">加载中…</p></div>
207
+ </section>
208
+ <section>
209
+ <h2>生命周期 <span class="sub">只配置是否跟随 dsh;所有资源强制跟随 daemon(停止 daemon 时一并停止)</span></h2>
210
+ <div id="lifecycle-rows">
211
+ <label class="life"><b>守护进程</b><input type="checkbox" data-life="daemon.followDsh"><span class="muted">跟随 dsh:最后一个 dsh 窗口退出后,空闲 10 分钟自动退出;关掉则一直运行到手动停止</span></label>
212
+ <label class="life"><b>代理引擎</b><input type="checkbox" data-life="proxy.followDsh"><span class="muted">跟随 dsh:没有 dsh 租约时拆除隧道(含系统层拦截)</span></label>
213
+ <label class="life"><b>程序(JVM)</b><input type="checkbox" data-life="programs.followDsh"><span class="muted">跟随 dsh:最后一个窗口退出后停止程序</span></label>
214
+ <label class="life"><b>调试会话</b><input type="checkbox" data-life="debug.followDsh"><span class="muted">跟随 dsh:最后一个窗口退出后断开调试</span></label>
215
+ </div>
216
+ <div class="row" style="margin-top:10px">
217
+ <span class="grow"></span>
218
+ <span class="muted" id="lifecycle-note"></span>
219
+ <button id="lifecycle-save">保存生命周期</button>
220
+ </div>
221
+ </section>
222
+ </div>
223
+
224
+ <div class="view" id="view-proxy" hidden>
225
+ <section>
226
+ <h2>ProxyBridge 组件 <span class="sub">系统层拦截所需;按需下载,缓存复用,不随插件打包</span></h2>
227
+ <div class="row">
228
+ <span id="bridge-pill" class="pill off">未知</span>
229
+ <span class="muted grow" id="bridge-detail"></span>
230
+ <button id="bridge-download">下载组件</button>
231
+ <button id="bridge-upload">选择 tgz 上传</button>
232
+ <input id="bridge-file" type="file" accept=".tgz,.tar.gz,application/gzip" hidden>
233
+ </div>
234
+ <div class="row" style="margin-top:8px">
235
+ <span id="bridge-health-pill" class="pill off">未检查</span>
236
+ <span class="muted grow" id="bridge-health-text"></span>
237
+ <button id="bridge-health-elevate" hidden>提权启动</button>
238
+ <button id="bridge-health-stop" hidden>停止拦截</button>
239
+ </div>
240
+ <div id="bridge-elevate-note" hidden></div>
241
+ <details id="bridge-health-more" style="margin-top:6px" hidden>
242
+ <summary class="muted" style="cursor:pointer">说明</summary>
243
+ <div class="muted" id="bridge-health-detail" style="margin-top:4px;white-space:pre-line"></div>
244
+ </details>
245
+ <div class="muted" id="bridge-hint" style="margin-top:6px"></div>
246
+ </section>
247
+ <section>
248
+ <h2>规则表 <span class="sub">全局规则:按机器生效、不区分工作区;保存经 daemon 的 CAS,多窗口同时改不会互相覆盖</span></h2>
249
+ <div class="row" style="margin-bottom:10px">
250
+ <span class="pill off" id="proxy-engine-pill">未知</span>
251
+ <span class="grow"></span>
252
+ <button id="proxy-engine-toggle" disabled>启动</button>
253
+ <span class="muted" id="proxy-revision"></span>
254
+ </div>
255
+ <div class="row" style="margin-bottom:10px">
256
+ <label class="muted">SOCKS 主机</label><input id="proxy-socks-host" class="narrow" placeholder="host">
257
+ <label class="muted">端口</label><input id="proxy-socks-port" class="narrow" placeholder="1080">
258
+ <span id="proxy-ping" class="pill off" role="status" title="">检测中…</span>
259
+ <label class="muted">监听端口</label><input id="proxy-listen" class="narrow" placeholder="11081">
260
+ </div>
261
+ <div id="proxy-banner"></div>
262
+ <table>
263
+ <thead>
264
+ <tr><th style="width:56px">启用</th><th style="width:170px">程序名称/路径</th><th>目标主机</th><th style="width:120px">端口</th><th style="width:88px">状态</th><th style="width:90px">来源</th><th></th></tr>
265
+ </thead>
266
+ <tbody id="proxy-rules"></tbody>
267
+ </table>
268
+ <div class="row" style="margin-top:10px">
269
+ <button id="proxy-add">+ 添加规则</button>
270
+ <span class="grow"></span>
271
+ <button id="bridge-restart" hidden>重启系统层拦截(可能提权)</button>
272
+ <button id="proxy-log-toggle">代理日志</button>
273
+ </div>
274
+ <pre id="proxy-log" hidden></pre>
275
+ </section>
276
+ </div>
277
+
278
+ <div class="view" id="view-ide" hidden>
279
+ <div class="ide-layout">
280
+ <aside class="ide-side" id="ide-side">
281
+ <ul id="ide-ws-list"></ul>
282
+ <p class="note">列表来自正在运行的 dsh</p>
283
+ </aside>
284
+ <div class="ide-main">
285
+ <div id="ide-stale" class="ide-stale" hidden><span id="ide-stale-text"></span><button id="ide-stale-close" type="button" title="关闭提示" aria-label="关闭提示">×</button></div>
286
+ <div id="ide-body" class="ide-body"><div id="ide-msg" class="ide-msg"><p class="empty">检查 dsh 状态…</p></div></div>
287
+ </div>
288
+ </div>
289
+ </div>
290
+ </main>
291
+ <div class="modal" id="confirm" hidden>
292
+ <div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="confirm-title">
293
+ <h3 id="confirm-title">停止守护进程?</h3>
294
+ <div class="modal-body" id="confirm-body"></div>
295
+ <div class="modal-actions">
296
+ <button id="confirm-cancel">取消</button>
297
+ <button class="danger" id="confirm-ok">停止</button>
298
+ </div>
299
+ </div>
300
+ </div>
301
+ <script>
302
+ (function () {
303
+ var TOKEN = ${token};
304
+ var VERSION = ${version};
305
+ var HOME = ${home};
306
+ var API_VERSION = ${apiVersion};
307
+ // 本进程运行的页面代码指纹(见 risd/build.js):/v1/health 的 uiBuild.loaded
308
+ // 变了说明 daemon 重启并加载了新代码,刷新即可;只有 disk 变说明源码改了但
309
+ // daemon 还是旧模块,刷新不会有效果,只能提示重启。
310
+ var PAGE_BUILD = ${uiBuild};
311
+ // 渲染本页的 daemon 进程身份:daemon 重启后 token 会变,本页的所有请求都会 401。
312
+ // 与 /v1/health 的 instance 对比即可发现自己是个「旧页面」并提示刷新。
313
+ var PAGE_INSTANCE = ${uiInstance};
314
+ var initialCwd = '';
315
+ try { initialCwd = new URLSearchParams(location.search).get('cwd') || ''; } catch { /* no URL API */ }
316
+ var state = { tab: 'overview', cwd: initialCwd || localStorage.getItem('risd.cwd') || '', view: null, logOn: false, logTimer: null, pollTimer: null, pingTimer: null, pingSeq: 0, healthTimer: null, elevateNote: null, dsh: null, dshAvailable: null, lifecycleDirty: false, proxyDirty: false, proxyRunning: false, stopBusy: false, elevateBusy: false, summary: { proxyRunning: false, programs: 0, debugs: 0 }, staleDismissed: {},
317
+ };
318
+ // The drift banner's current message and the message the user closed: a closed
319
+ // hint must not pop back every 5 s, but a NEW kind of drift still has to warn.
320
+ var driftMessage = '';
321
+ var driftDismissedFor = '';
322
+ // m11421: 源码比进程新(插件版本已更新)时光刷新没用——旧进程的模块图不会变,
323
+ // 必须先重启 daemon 再加载本页,所以横幅的按钮在 restart 模式下是「重启并刷新」。
324
+ var driftMode = 'reload';
325
+ // One name per page load, not per iframe document: the embedded IDE claims a Web
326
+ // Lock named after this value, and rebuilding the iframe (workspace switch, tab
327
+ // re-entry) must not race the previous document's lock and flash 「RIS-IDE 已在
328
+ // 另一个窗口打开」. The standalone IDE window keeps its workspace-keyed name, so
329
+ // the two paths never contend (review C-P2-6).
330
+ var IDE_WNAME = 'risd-ide-' + Math.random().toString(36).slice(2, 8);
331
+
332
+ function api(path, options) {
333
+ options = options || {};
334
+ var headers = { authorization: 'Bearer ' + TOKEN, 'x-risd-api-version': API_VERSION };
335
+ if (options.body !== undefined) headers['content-type'] = 'application/json';
336
+ return fetch(path, {
337
+ method: options.method || 'GET',
338
+ headers: headers,
339
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
340
+ }).then(function (res) {
341
+ return res.json().catch(function () { return {}; }).then(function (body) {
342
+ if (!res.ok || body.ok === false) {
343
+ // 401 = the daemon restarted and re-issued its token: this page can never
344
+ // recover on its own, so say so instead of failing silently on every call.
345
+ // Do not clobber a richer message from checkBuild (it may be counting
346
+ // unsaved editor buffers and showing 「保存所有文件」): the 401 timers
347
+ // fire every few seconds, the drift check every five.
348
+ if (res.status === 401 && driftMessage.indexOf('未保存') === -1 && driftMessage.indexOf('无法确认') === -1) {
349
+ showDrift('维护页令牌已失效(daemon 已重启):点右侧刷新');
350
+ }
351
+ var error = new Error(body.message || body.error || ('HTTP ' + res.status));
352
+ error.status = res.status;
353
+ error.body = body;
354
+ throw error;
355
+ }
356
+ return body;
357
+ });
358
+ });
359
+ }
360
+
361
+ function el(id) { return document.getElementById(id); }
362
+ function esc(value) {
363
+ return String(value === undefined || value === null ? '' : value)
364
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
365
+ .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
366
+ }
367
+ // The class is NOT free text: a rule's source field is written to proxy.json by
368
+ // whatever plugin/editor touched it, so an unescaped class could break out of
369
+ // the attribute and run script in a page that carries the daemon token
370
+ // (review C-P2-4).
371
+ function pill(text, cls) { return '<span class="pill ' + esc(cls || '') + '">' + esc(text) + '</span>'; }
372
+ function hhmmss(ms) {
373
+ var total = Math.max(0, Math.floor(ms / 1000));
374
+ var h = Math.floor(total / 3600), m = Math.floor((total % 3600) / 60), s = total % 60;
375
+ return (h > 0 ? h + 'h' : '') + m + 'm' + s + 's';
376
+ }
377
+ function banner(kind, text) {
378
+ // Same reasoning as pill(): the kind argument reaches the class attribute, so only the
379
+ // three shapes this page uses may pass (review C-P2-4).
380
+ var shape = kind === 'err' || kind === 'warn' || kind === 'ok' ? kind : 'warn';
381
+ return text ? '<div class="banner ' + shape + '">' + esc(text) + '</div>' : '';
382
+ }
383
+
384
+ // ---- header ----
385
+ function loadDaemon() {
386
+ return api('/v1/health').then(function (body) {
387
+ var home = body.home || HOME;
388
+ el('daemon-pill').className = 'pill on';
389
+ el('daemon-pill').textContent = '运行中';
390
+ el('daemon-sub').textContent = 'pid ' + body.pid + ' · 已运行 ' + hhmmss(body.uptimeMs);
391
+ el('daemon-detail').textContent = 'v' + body.version + ' · API v' + body.apiVersion +
392
+ ' · ' + (body.port ? '127.0.0.1:' + body.port : '') + ' · 租约 ' + body.leases.count +
393
+ ' · ' + (body.engine && body.engine.owned === true ? '引擎由本 daemon 托管' : '引擎由插件托管');
394
+ }).catch(function (error) {
395
+ el('daemon-pill').className = 'pill warn';
396
+ el('daemon-pill').textContent = '不可达';
397
+ el('daemon-sub').textContent = '';
398
+ el('daemon-detail').textContent = error.message;
399
+ });
400
+ }
401
+
402
+ // ---- overview ----
403
+ function proxySummary() {
404
+ return api('/v1/proxy?cwd=' + encodeURIComponent(state.cwd || HOME)).then(function (view) {
405
+ el('proxy-pill').className = 'pill ' + (view.running ? 'on' : 'off');
406
+ el('proxy-pill').textContent = view.running ? '运行中' : '未运行';
407
+ el('proxy-sub').textContent = view.running
408
+ ? 'pid ' + view.pid + ' · 监听 ' + view.listenPort
409
+ : '监听端口 ' + view.listenPort + ' · 规则 ' + (view.rules || []).length + ' 条';
410
+ el('proxy-detail').textContent = 'revision ' + view.revision;
411
+ state.summary.proxyRunning = view.running === true;
412
+ if (engineBusy) {
413
+ paintEngineButtons();
414
+ } else {
415
+ var engineToggle = el('engine-toggle');
416
+ if (engineToggle) {
417
+ var running = state.summary.proxyRunning === true;
418
+ engineToggle.disabled = false;
419
+ engineToggle.removeAttribute('aria-busy');
420
+ engineToggle.textContent = running ? '停止' : '启动';
421
+ engineToggle.className = running ? 'danger' : '';
422
+ engineToggle.title = running ? '停止引擎、系统层拦截与 git 代理' : '按当前规则表启动代理引擎(系统层拦截可能需要提权)';
423
+ }
424
+ }
425
+ state.cwd = view.workspace || state.cwd;
426
+ if (state.cwd) localStorage.setItem('risd.cwd', state.cwd);
427
+ return view;
428
+ }).catch(function (error) {
429
+ el('proxy-pill').className = 'pill warn';
430
+ el('proxy-pill').textContent = '未知';
431
+ el('proxy-sub').textContent = error.message;
432
+ return null;
433
+ });
434
+ }
435
+
436
+ function loadProjects() {
437
+ var box = el('projects');
438
+ return api('/v1/workspaces').then(function (body) {
439
+ var list = (body.workspaces || []).slice();
440
+ if (state.cwd && list.indexOf(state.cwd) === -1) list.unshift(state.cwd);
441
+ if (list.length === 0) { box.innerHTML = '<p class="empty">还没有记录到工作区:先在 dsh 面板里打开一次,或在「代理」页签里填路径。</p>'; return; }
442
+ return Promise.all(list.map(function (cwd) {
443
+ return api('/v1/programs?cwd=' + encodeURIComponent(cwd)).then(function (listed) {
444
+ return { cwd: cwd, programs: (listed.programs || []).filter(function (row) { return row.running && row.running.alive !== false; }) };
445
+ }).catch(function (error) { return { cwd: cwd, error: error.message }; });
446
+ })).then(function (groups) {
447
+ var html = '';
448
+ groups.forEach(function (group) {
449
+ if (group.error) { html += '<div class="group-title">' + esc(group.cwd) + '</div><p class="empty">' + esc(group.error) + '</p>'; return; }
450
+ if (group.programs.length === 0) return;
451
+ html += '<div class="group-title">' + esc(group.cwd) + '</div><ul class="programs">';
452
+ group.programs.forEach(function (row) {
453
+ html += '<li><span style="min-width:220px">' + esc(row.name || row.id) + '</span>' + pill(row.kind || '') +
454
+ '<span class="muted">pid ' + esc(row.running && row.running.pid || '') + '</span><span class="grow"></span>' +
455
+ '<button data-stop-program="' + esc(row.id) + '" data-cwd="' + esc(group.cwd) + '">停止</button></li>';
456
+ });
457
+ html += '</ul>';
458
+ });
459
+ box.innerHTML = html || '<p class="empty">没有正在运行的项目。</p>';
460
+ state.summary.programs = groups.reduce(function (total, group) { return total + (group.programs ? group.programs.length : 0); }, 0);
461
+ });
462
+ }).catch(function (error) { box.innerHTML = '<p class="empty">' + esc(error.message) + '</p>'; });
463
+ }
464
+
465
+ function loadDebugs() {
466
+ var box = el('debugs');
467
+ return api('/v1/debug', { method: 'POST', body: { action: 'sessions' } }).then(function (body) {
468
+ var rows = body.sessions || [];
469
+ var stale = body.stale || [];
470
+ state.summary.debugs = rows.length;
471
+ if (rows.length === 0 && stale.length === 0) { box.innerHTML = '<p class="empty">没有调试中的进程。</p>'; return; }
472
+ var html = '';
473
+ if (stale.length > 0) {
474
+ // Review D3: a session kept only on disk (no JVM, no attach) used to be
475
+ // invisible here, so its breakpoint set had no page to clear it from.
476
+ html += '<ul class="programs">';
477
+ stale.forEach(function (row) {
478
+ html += '<li><span style="min-width:220px">' + esc(row.logPath) + '</span>' +
479
+ '<span class="muted">已断开 · 断点 ' + esc((row.breakpoints || []).length) + ' 个</span><span class="grow"></span>' +
480
+ '<button data-forget-debug="' + esc(row.logPath) + '">清除记录</button></li>';
481
+ });
482
+ html += '</ul>';
483
+ }
484
+ if (rows.length > 0) html += '<ul class="programs">';
485
+ rows.forEach(function (row) {
486
+ var target = row.name || row.id || row.logPath;
487
+ html += '<li><span style="min-width:220px">' + esc(target) + '</span>' +
488
+ (row.port ? '<span class="muted">JDWP ' + esc(row.port) + '</span>' : '') +
489
+ '<span class="muted">' + esc(row.cwd || '') + '</span><span class="grow"></span>' +
490
+ (row.cwd && row.id ? '<button class="danger" data-stop-debug="' + esc(row.id) + '" data-cwd="' + esc(row.cwd) + '">停止</button>' : '') +
491
+ '<button data-detach="' + esc(row.logPath) + '">断开</button></li>';
492
+ });
493
+ if (rows.length > 0) html += '</ul>';
494
+ box.innerHTML = html;
495
+ }).catch(function (error) { box.innerHTML = '<p class="empty">' + esc(error.message) + '</p>'; });
496
+ }
497
+
498
+ /** Fill the lifecycle checkboxes from the daemon's config (GET returns it). */
499
+ function loadLifecycle() {
500
+ // The 4 s overview refresh runs while the form is open; it must not overwrite a
501
+ // checkbox the user just toggled, or the form looks broken ("勾了又弹回去").
502
+ // Saving clears the flag (review C-P2-3).
503
+ if (state.lifecycleDirty === true) return Promise.resolve(state.lifecycle || null);
504
+ return api('/v1/config').then(function (body) {
505
+ var policy = body.lifecycle || {};
506
+ document.querySelectorAll('#lifecycle-rows input[data-life]').forEach(function (box) {
507
+ var parts = box.getAttribute('data-life').split('.');
508
+ var resource = policy[parts[0]] || {};
509
+ box.checked = resource[parts[1]] === true;
510
+ });
511
+ state.lifecycle = policy;
512
+ el('lifecycle-note').textContent = '';
513
+ return policy;
514
+ }).catch(function (error) { el('lifecycle-note').textContent = error.message; });
515
+ }
516
+
517
+ function lifecycleFromBoxes() {
518
+ var policy = { daemon: {}, proxy: {}, programs: {}, debug: {} };
519
+ document.querySelectorAll('#lifecycle-rows input[data-life]').forEach(function (box) {
520
+ var parts = box.getAttribute('data-life').split('.');
521
+ if (policy[parts[0]] === undefined) policy[parts[0]] = {};
522
+ policy[parts[0]][parts[1]] = box.checked;
523
+ });
524
+ return policy;
525
+ }
526
+
527
+ function saveLifecycle() {
528
+ var policy = lifecycleFromBoxes();
529
+ return api('/v1/config', { method: 'POST', body: { lifecycle: policy } }).then(function (body) {
530
+ state.lifecycle = body.lifecycle || policy;
531
+ state.lifecycleDirty = false;
532
+ el('lifecycle-note').textContent = '已保存';
533
+ setTimeout(function () { if (el('lifecycle-note')) el('lifecycle-note').textContent = ''; }, 2500);
534
+ return loadLifecycle();
535
+ }).catch(function (error) { el('lifecycle-note').textContent = '保存失败:' + error.message; });
536
+ }
537
+
538
+ function refreshOverview() {
539
+ loadDaemon();
540
+ return Promise.all([proxySummary(), loadProjects(), loadDebugs(), loadLifecycle()]);
541
+ }
542
+
543
+ // ---- proxy tab ----
544
+ /** 1521 / 1521,1000-1010 / *;其它写法是引擎用不了的笔误。 */
545
+ function portSpecOk(value) {
546
+ var spec = String(value === undefined || value === null ? '' : value).trim();
547
+ if (spec === '') return false;
548
+ if (spec === '*') return true;
549
+ return spec.split(',').every(function (part) {
550
+ part = part.trim();
551
+ if (/^[0-9]+$/.test(part)) {
552
+ var single = Number(part);
553
+ return single >= 1 && single <= 65535;
554
+ }
555
+ var range = /^([0-9]+)-([0-9]+)$/.exec(part);
556
+ if (range === null) return false;
557
+ var low = Number(range[1]);
558
+ var high = Number(range[2]);
559
+ return low >= 1 && high <= 65535 && low <= high;
560
+ });
561
+ }
562
+ /**
563
+ * What the engine will do with this row right now — the answer to 「这行到底生效了
564
+ * 没有」 without reading the log. Order matters: an incomplete row is never
565
+ * 「生效」, and a complete row waits for the engine.
566
+ */
567
+ function ruleStatus(rule) {
568
+ if (rule.enabled === false) return { cls: 'off', text: '未启用' };
569
+ var missing = [];
570
+ if (!String(rule.program || '').trim()) missing.push('程序');
571
+ if (!String(rule.hosts || '').trim()) missing.push('IP');
572
+ if (!String(rule.ports || '').trim()) missing.push('端口');
573
+ if (missing.length > 0) return { cls: 'err', text: '缺' + missing.join('/') };
574
+ if (!portSpecOk(rule.ports)) return { cls: 'err', text: '端口格式' };
575
+ return state.proxyRunning === true
576
+ ? { cls: 'on', text: '生效' }
577
+ : { cls: 'off', text: '待启动' };
578
+ }
579
+ /**
580
+ * A row's origin at a glance. The side matters on WSL: java.exe and java are two
581
+ * rows because each side's ProxyBridge matches a different image name.
582
+ */
583
+ function sourceText(rule) {
584
+ var source = String(rule.source || 'user');
585
+ if (rule.side === 'local') return source + '·wsl';
586
+ if (rule.side === 'windows') return source + '·win';
587
+ return source;
588
+ }
589
+ function ruleRow(rule, index) {
590
+ var status = ruleStatus(rule);
591
+ return '<tr data-index="' + index + '">' +
592
+ '<td><input type="checkbox" data-field="enabled"' + (rule.enabled === false ? '' : ' checked') + '></td>' +
593
+ '<td><input type="text" data-field="program" value="' + esc(rule.program) + '"></td>' +
594
+ '<td><input type="text" data-field="hosts" value="' + esc(rule.hosts) + '"></td>' +
595
+ '<td><input type="text" data-field="ports" value="' + esc(rule.ports) + '"></td>' +
596
+ '<td>' + pill(status.text, status.cls) + '</td>' +
597
+ '<td>' + pill(sourceText(rule)) + (rule.shadow ? ' ' + pill('shadow', 'warn') : '') + (rule.direct ? ' ' + pill('direct', 'warn') : '') + '</td>' +
598
+ '<td class="actions"><button data-remove="' + index + '">删除</button></td>' +
599
+ '</tr>';
600
+ }
601
+
602
+ /**
603
+ * The restart button is noise when nothing is stale, and the whole point when
604
+ * something is: show it only for a failed/incomplete reload and put the reason in
605
+ * the tooltip (a click costs a UAC prompt on Windows and sudo on this side).
606
+ */
607
+ function setBridgeStale(reason) {
608
+ var stale = /未重载|旧规则|需要提权|未能重载|未重启|未能停止/.test(String(reason || ''));
609
+ var button = el('bridge-restart');
610
+ button.hidden = !stale;
611
+ button.title = stale
612
+ ? '为什么要重启:' + reason + '(点一下会停止系统层拦截并按当前规则表重新启动;Windows 会弹一次 UAC,本侧需要 sudo)'
613
+ : '';
614
+ }
615
+
616
+ function renderProxyTab(view) {
617
+ state.view = view;
618
+ state.proxyRunning = view.running === true;
619
+ setBridgeStale(state.lastReloadNote || '');
620
+ el('proxy-socks-host').value = view.socks ? view.socks.host : '';
621
+ el('proxy-socks-port').value = view.socks ? view.socks.port : '';
622
+ el('proxy-listen').value = view.listenPort;
623
+ el('proxy-revision').textContent = 'revision ' + view.revision;
624
+ var enginePill = el('proxy-engine-pill');
625
+ if (enginePill) {
626
+ enginePill.className = 'pill ' + (state.proxyRunning ? 'on' : 'off');
627
+ enginePill.textContent = state.proxyRunning ? '代理运行中' : '代理未运行';
628
+ enginePill.title = state.proxyRunning ? '引擎在跑:合规的行已经生效' : '保存后如果规则完整会自动启动';
629
+ }
630
+ if (engineBusy) {
631
+ paintEngineButtons();
632
+ } else {
633
+ var engineToggle = el('proxy-engine-toggle');
634
+ if (engineToggle) {
635
+ engineToggle.disabled = false;
636
+ engineToggle.removeAttribute('aria-busy');
637
+ engineToggle.textContent = state.proxyRunning ? '停止' : '启动';
638
+ engineToggle.className = state.proxyRunning ? 'danger' : '';
639
+ engineToggle.title = state.proxyRunning
640
+ ? '停止引擎、系统层拦截与 git 代理'
641
+ : '按当前规则表启动(保存后规则完整会自动启动;系统层拦截可能需要提权)';
642
+ }
643
+ }
644
+ var rules = view.rules || [];
645
+ el('proxy-rules').innerHTML = rules.length === 0
646
+ ? '<tr><td colspan="7" class="empty">没有规则。系统代理至少需要一条启用且带程序/IP/端口的规则。</td></tr>'
647
+ : rules.map(ruleRow).join('');
648
+ }
649
+
650
+ function rulesFromTable() {
651
+ var rows = [];
652
+ el('proxy-rules').querySelectorAll('tr[data-index]').forEach(function (tr) {
653
+ var base = (state.view && state.view.rules || [])[Number(tr.getAttribute('data-index'))] || {};
654
+ var rule = Object.assign({}, base);
655
+ if (!rule.id) rule.id = 'user-' + Math.random().toString(36).slice(2, 9);
656
+ rule.program = tr.querySelector('[data-field="program"]').value.trim();
657
+ rule.hosts = tr.querySelector('[data-field="hosts"]').value.trim();
658
+ rule.ports = tr.querySelector('[data-field="ports"]').value.trim();
659
+ rule.enabled = tr.querySelector('[data-field="enabled"]').checked;
660
+ if (!rule.source) rule.source = 'user';
661
+ rows.push(rule);
662
+ });
663
+ return rows;
664
+ }
665
+
666
+ /** Everything the engine needs before a save is worth writing (and before auto-start). */
667
+ function proxyFormIssues() {
668
+ var issues = [];
669
+ var host = el('proxy-socks-host').value.trim();
670
+ var socksPort = Number(el('proxy-socks-port').value);
671
+ if (host === '') issues.push('代理服务器地址为空');
672
+ else if (/\s/.test(host)) issues.push('代理服务器地址含空格');
673
+ if (!(socksPort >= 1 && socksPort <= 65535)) issues.push('代理服务器端口需为 1-65535');
674
+ var listenPort = Number(el('proxy-listen').value);
675
+ if (!(listenPort >= 1 && listenPort <= 65535)) issues.push('监听端口需为 1-65535');
676
+ rulesFromTable().forEach(function (rule, index) {
677
+ if (rule.enabled === false) return;
678
+ var missing = [];
679
+ if (!rule.program) missing.push('程序');
680
+ if (!rule.hosts) missing.push('IP');
681
+ if (!rule.ports) missing.push('端口');
682
+ if (missing.length > 0) issues.push('第 ' + (index + 1) + ' 行缺' + missing.join('/'));
683
+ else if (!portSpecOk(rule.ports)) issues.push('第 ' + (index + 1) + ' 行端口格式不对');
684
+ });
685
+ return issues;
686
+ }
687
+
688
+ /** A complete, enabled row is what makes starting the engine worth doing. */
689
+ function hasActionableRule(view) {
690
+ return (view && view.rules || []).some(function (rule) {
691
+ return rule.enabled !== false && String(rule.program || '').trim() !== '' &&
692
+ String(rule.hosts || '').trim() !== '' && portSpecOk(rule.ports);
693
+ });
694
+ }
695
+
696
+ /**
697
+ * 「勾选的配置不为空、有效就自动保存并启动」:editing is the save. A partially
698
+ * filled row is not an error the user must dismiss, so the banner explains what is
699
+ * still missing and the save happens once it is complete.
700
+ */
701
+ var autoSaveTimer = null;
702
+ // Rapid edits can outrun a POST: the second write would carry the revision of the
703
+ // first (409 against ourselves). One save in flight, then re-run if the form moved.
704
+ var saveInFlight = null;
705
+ var savePending = false;
706
+ function scheduleProxySave() {
707
+ state.proxyDirty = true;
708
+ state.editVersion = (state.editVersion || 0) + 1;
709
+ if (autoSaveTimer !== null) clearTimeout(autoSaveTimer);
710
+ autoSaveTimer = setTimeout(function () {
711
+ autoSaveTimer = null;
712
+ autoSaveProxy();
713
+ }, 700);
714
+ }
715
+ function autoSaveProxy() {
716
+ if (state.tab !== 'proxy') return;
717
+ var issues = proxyFormIssues();
718
+ if (issues.length > 0) {
719
+ el('proxy-banner').innerHTML = banner('warn', '还没保存:' + issues.join(';'));
720
+ return;
721
+ }
722
+ saveRules({ auto: true });
723
+ }
724
+
725
+ /**
726
+ * After a successful save, bring the tunnel up — that is the 「并启动」 half. A
727
+ * bridge that needs elevation is reported as a note (the restart button appears
728
+ * from setBridgeStale), never as a silent failure.
729
+ */
730
+ function maybeStartProxy(view) {
731
+ if (!view || view.running === true || hasActionableRule(view) === false) return Promise.resolve(null);
732
+ var version = state.editVersion || 0;
733
+ el('proxy-banner').innerHTML = banner('ok', '规则已保存,正在启动代理…');
734
+ return api('/v1/action', { method: 'POST', body: { action: 'start', cwd: state.cwd } }).then(function (response) {
735
+ var result = (response && response.result) || {};
736
+ var redirector = result.redirector || {};
737
+ var skipped = Array.isArray(redirector.skipped) ? redirector.skipped : [];
738
+ var note = skipped.length > 0
739
+ ? '系统层拦截需要提权:' + skipped.map(function (item) { return item.side + ':' + item.reason; }).join(';')
740
+ : (typeof result.reloadNote === 'string' ? result.reloadNote : '');
741
+ state.lastReloadNote = note;
742
+ if ((state.editVersion || 0) !== version) return null;
743
+ return loadProxyTab().then(function () {
744
+ el('proxy-banner').innerHTML = note
745
+ ? banner('warn', '规则已保存;' + note + '(可点「重启系统层拦截」重试)')
746
+ : banner('ok', '规则已保存并已启动代理');
747
+ });
748
+ }).catch(function (error) {
749
+ el('proxy-banner').innerHTML = banner('warn', '规则已保存,但代理启动失败:' + error.message);
750
+ return null;
751
+ });
752
+ }
753
+
754
+ function loadProxyTab() {
755
+ // The rule table is machine-wide: no workspace picker. The workspace only tags
756
+ // rows for bookkeeping, so the daemon falls back to its own home when omitted.
757
+ var cwd = state.cwd || '';
758
+ return api('/v1/proxy' + (cwd ? '?cwd=' + encodeURIComponent(cwd) : '')).then(function (view) {
759
+ state.cwd = view.workspace || cwd;
760
+ localStorage.setItem('risd.cwd', state.cwd);
761
+ renderProxyTab(view);
762
+ // A view that just came from the daemon is the saved state by definition.
763
+ state.proxyDirty = false;
764
+ el('proxy-banner').innerHTML = '';
765
+ refreshPing();
766
+ loadBundle();
767
+ // A save switches enforcement in the background; a failure from an earlier
768
+ // save is reported here rather than blocking that save (m10585).
769
+ if (view.bridge && view.bridge.ok === false && view.bridge.note) setBridgeStale(view.bridge.note);
770
+ }).catch(function (error) { el('proxy-banner').innerHTML = banner('err', error.message); });
771
+ }
772
+
773
+ /**
774
+ * Refresh the base revision without repainting: a 409 usually means our own earlier
775
+ * save bumped the table while the user kept typing, and repainting here would
776
+ * replace that newer text with the version we failed to write.
777
+ */
778
+ function refreshProxyView() {
779
+ var cwd = state.cwd || '';
780
+ return api('/v1/proxy' + (cwd ? '?cwd=' + encodeURIComponent(cwd) : '')).then(function (view) {
781
+ state.cwd = view.workspace || cwd;
782
+ state.view = view;
783
+ return view;
784
+ });
785
+ }
786
+
787
+ function saveRules(options) {
788
+ var auto = !!(options && options.auto);
789
+ if (saveInFlight !== null) { savePending = true; return saveInFlight; }
790
+ var version = state.editVersion || 0;
791
+ var cwd = state.cwd || '';
792
+ var body = {
793
+ cwd: cwd || undefined,
794
+ revision: state.view ? state.view.revision : '',
795
+ config: {
796
+ socks: { host: el('proxy-socks-host').value.trim(), port: Number(el('proxy-socks-port').value) || 0 },
797
+ listenPort: Number(el('proxy-listen').value) || 0,
798
+ rules: rulesFromTable(),
799
+ },
800
+ };
801
+ var run = api('/v1/proxy', { method: 'POST', body: body }).then(function (result) {
802
+ state.lastReloadNote = result.reloadNote || '';
803
+ // Typing during the POST is a fresh edit, not a save of the old text: repainting
804
+ // now would throw the new text away (it also overwrote the input the user was
805
+ // still typing in). Write the newer form instead.
806
+ if ((state.editVersion || 0) !== version) {
807
+ savePending = true;
808
+ return null;
809
+ }
810
+ state.proxyDirty = false;
811
+ // Reload first, then show the outcome: loadProxyTab clears the banner itself.
812
+ return loadProxyTab().then(function () {
813
+ el('proxy-banner').innerHTML = banner(result.reloadNote ? 'warn' : 'ok',
814
+ (auto ? '已自动保存' : '已保存') + '(revision ' + result.revision + ')' +
815
+ (result.reloadNote ? ' · ' + result.reloadNote : ''));
816
+ return maybeStartProxy(state.view);
817
+ });
818
+ });
819
+ saveInFlight = run.then(function (value) {
820
+ saveInFlight = null;
821
+ if (savePending === true) { savePending = false; scheduleProxySave(); }
822
+ return value;
823
+ }, function (error) {
824
+ saveInFlight = null;
825
+ var retryPending = savePending === true;
826
+ savePending = false;
827
+ if (error.status === 409) {
828
+ // Our own in-flight save bumped the revision: our edits are newer than the
829
+ // table we wrote, so reload and write again once (a real foreign edit also
830
+ // lands here, and the retry then reports the fresh table instead of a loop).
831
+ // Rebasing on the fresh revision (no repaint) keeps the text the user is
832
+ // still typing and writes exactly one more time.
833
+ if (options && options.retried !== true) {
834
+ return refreshProxyView().then(function () { return saveRules({ auto: auto, retried: true }); });
835
+ }
836
+ // Reload first, then show the conflict: loadProxyTab() rewrites the banner,
837
+ // so the old order made the 409 message visible for ~50 ms (review C-P1-4).
838
+ setTimeout(function () {
839
+ loadProxyTab().then(function () { el('proxy-banner').innerHTML = banner('err', error.message) })
840
+ }, 50)
841
+ return
842
+ }
843
+ if (retryPending === true) scheduleProxySave(); else el('proxy-banner').innerHTML = banner('err', error.message)
844
+ });
845
+ return saveInFlight;
846
+ }
847
+
848
+ function logToggle() {
849
+ state.logOn = !state.logOn;
850
+ el('proxy-log').hidden = !state.logOn;
851
+ el('proxy-log-toggle').textContent = state.logOn ? '停止日志' : '代理日志';
852
+ syncLogTimer();
853
+ }
854
+ // m12313: the component card is timer-driven — no manual re-check. Two caches sit
855
+ // behind the route: the component snapshot (file + version probes) for 30 s, and
856
+ // the interception status for 5 s — so a 10 s poll re-detects the bridge each
857
+ // tick but does not probe the component files every time (评审 20261109-2326
858
+ // 客户端 P2).
859
+ function syncHealthTimer() {
860
+ var wanted = state.tab === 'proxy' && document.hidden !== true
861
+ if (wanted && state.healthTimer === null) {
862
+ state.healthTimer = setInterval(function () { void loadHealth(false) }, 10000)
863
+ } else if (!wanted && state.healthTimer !== null) {
864
+ clearInterval(state.healthTimer)
865
+ state.healthTimer = null
866
+ }
867
+ }
868
+ // The tail costs up to 40 KB every 2 s: poll only while the pane is actually on
869
+ // screen (proxy tab, page visible) and pause on a hidden tab instead of keeping
870
+ // the timer alive off-screen (review C-P2-3).
871
+ function syncLogTimer() {
872
+ var wanted = state.logOn === true && state.tab === 'proxy' && document.hidden !== true;
873
+ if (wanted && state.logTimer === null) {
874
+ pollLog();
875
+ state.logTimer = setInterval(pollLog, 2000);
876
+ } else if (!wanted && state.logTimer !== null) {
877
+ clearInterval(state.logTimer);
878
+ state.logTimer = null;
879
+ }
880
+ }
881
+ function pollLog() {
882
+ api('/v1/proxy/log?bytes=40960').then(function (body) {
883
+ var pre = el('proxy-log');
884
+ pre.textContent = body.text || '(空)';
885
+ pre.scrollTop = pre.scrollHeight;
886
+ }).catch(function (error) { el('proxy-log').textContent = error.message; });
887
+ }
888
+
889
+ // ---- ProxyBridge bundle (m09120 ③) ----
890
+ // The binaries are no longer shipped in the package: they are downloaded once into
891
+ // <proxy home>/proxybridge/bundle and reused. When the mirror is unreachable the
892
+ // card names the URL and accepts the same .tgz by hand.
893
+ var bundlePoll = null;
894
+ // Remembered across renders: a failed download repeats only its error, so without
895
+ // these the card would lose the manual URLs that make it useful in the first place
896
+ // (review C3-P2-12), and the reinstall button would not know it is a reinstall.
897
+ var lastBundleUrls = [];
898
+ var lastBundleInstalled = false;
899
+ function renderBundle(status) {
900
+ var pill = el('bridge-pill');
901
+ var detail = el('bridge-detail');
902
+ var hint = el('bridge-hint');
903
+ var button = el('bridge-download');
904
+ var upload = el('bridge-upload');
905
+ if (!pill) return;
906
+ var installed = status.installed === true;
907
+ var cls = 'pill';
908
+ var text = '未知';
909
+ if (status.downloading === true) { cls += ' warn'; text = '下载中…'; }
910
+ else if (installed) { cls += ' on'; text = '已安装'; }
911
+ else if (status.result && status.result.ok === false) { cls += ' err'; text = '下载失败'; }
912
+ else { cls += ' off'; text = '未安装'; }
913
+ pill.className = cls;
914
+ pill.textContent = text;
915
+ lastBundleInstalled = installed;
916
+ // The install directory is an implementation detail; the card answers 「装没装、
917
+ // 几个文件」 and keeps the paths in the hint only when something is missing.
918
+ detail.textContent = installed
919
+ ? '已安装 · 文件 ' + (status.files || []).length + ' 个'
920
+ : (status.downloading === true ? '正在下载并校验…' : '系统层拦截在首次使用时需要这组文件');
921
+ // Installed is the steady state: the card then only reports 「装了几个文件」.
922
+ // Download/upload are recovery paths for a missing bundle, so they disappear
923
+ // once it is installed (m10585).
924
+ button.hidden = installed;
925
+ upload.hidden = installed;
926
+ button.disabled = status.downloading === true;
927
+ button.textContent = '下载组件';
928
+ var urls = Array.isArray(status.urls) === true && status.urls.length > 0
929
+ ? status.urls
930
+ : [status.url].filter(function (item) { return typeof item === 'string' && item !== ''; });
931
+ if (urls.length > 0) lastBundleUrls = urls.slice();
932
+ else urls = lastBundleUrls.slice();
933
+ if (installed) { hint.textContent = ''; hint.style.whiteSpace = ''; return; }
934
+ var lines = ['下载地址(优先 Gitee,失败自动换 GitHub):'];
935
+ urls.forEach(function (item) { lines.push(' ' + item); });
936
+ if (status.result && status.result.ok === false && status.result.error) lines.push('失败原因:' + status.result.error);
937
+ if (urls.length > 0) lines.push('也可在浏览器打开上面的地址下载 tgz,再点「选择 tgz 上传」。');
938
+ hint.textContent = lines.join('\\n');
939
+ hint.style.whiteSpace = 'pre-line';
940
+ }
941
+ // m12313/m12508: one short line at a glance; the long explanation (sudo command,
942
+ // degraded JVM/env plan) lives in a collapsed <details> under it.
943
+ // m12923: the elevation note is card-owned. A terminal note lives until the helper
944
+ // script removes its state file (or the side starts intercepting); other outcomes
945
+ // fade out on their own, so the card never keeps a stale sentence.
946
+ function renderElevateNote(health) {
947
+ var box = el('bridge-elevate-note')
948
+ if (!box) return
949
+ var note = state.elevateNote
950
+ if (!note) { box.hidden = true; box.innerHTML = ''; return }
951
+ var interception = (health && health.interception) || {}
952
+ var elevations = (health && health.elevations) || {}
953
+ var side = note.side
954
+ var active = !!(side && elevations[side] && elevations[side].active === true)
955
+ if (active) note.seenActive = true
956
+ if (side && interception[side] === true) {
957
+ state.elevateNote = null
958
+ } else if (note.terminal === true) {
959
+ // Seen open once and now gone = the window closed after the password.
960
+ if (note.seenActive === true && active === false) state.elevateNote = null
961
+ // Never seen open within 8 s: the script or the terminal failed silently.
962
+ else if (note.seenActive !== true && Date.now() - note.at > 8000) state.elevateNote = null
963
+ } else if (Date.now() - note.at > 12000) {
964
+ state.elevateNote = null
965
+ }
966
+ note = state.elevateNote
967
+ if (!note) { box.hidden = true; box.innerHTML = ''; return }
968
+ box.hidden = false
969
+ box.innerHTML = banner(note.kind, note.text)
970
+ }
971
+
972
+ function renderHealth(health) {
973
+ var pill = el('bridge-health-pill')
974
+ var text = el('bridge-health-text')
975
+ var stop = el('bridge-health-stop')
976
+ var more = el('bridge-health-more')
977
+ var detail = el('bridge-health-detail')
978
+ if (!pill || !text) return
979
+ var engineRunning = health && health.engineRunning === true
980
+ var stray = (health && health.stray) || { linux: false, windows: false }
981
+ var isStray = stray.linux === true || stray.windows === true
982
+ var sides = (health && health.sides) || {}
983
+ var interception = (health && health.interception) || { linux: false, windows: false }
984
+ var names = { linux: 'Linux', windows: 'Windows' }
985
+ var elevate = el('bridge-health-elevate')
986
+ stop.hidden = !isStray
987
+ // A request in flight owns its button: the 10 s health poll must not re-enable
988
+ // it, or a second click fires another stop/elevation while the first is still
989
+ // waiting (评审 20261109-2326 客户端 P2).
990
+ stop.disabled = state.stopBusy === true
991
+ var missingNow = ['linux', 'windows'].filter(function (key) {
992
+ return sides[key] && sides[key].applicable !== false && interception[key] !== true
993
+ })
994
+ if (elevate) {
995
+ elevate.hidden = !(engineRunning === true && isStray !== true && missingNow.length > 0)
996
+ elevate.disabled = state.elevateBusy === true
997
+ if (state.elevateBusy !== true) elevate.textContent = '提权启动'
998
+ }
999
+ var lines = []
1000
+ function notes(message) { if (message) lines.push(message) }
1001
+ function planNotes() {
1002
+ var commands = []
1003
+ var lastStart = health && health.lastStart
1004
+ if (lastStart && Array.isArray(lastStart.skipped)) {
1005
+ lastStart.skipped.forEach(function (item) {
1006
+ if (item && typeof item.command === 'string' && item.command !== '') commands.push(item.command)
1007
+ })
1008
+ }
1009
+ var degrade = health && health.degrade
1010
+ var missing = ['linux', 'windows'].filter(function (key) {
1011
+ return sides[key] && sides[key].applicable !== false && interception[key] !== true
1012
+ })
1013
+ if (missing.length === 0) return
1014
+ var command = commands[0] || (degrade && degrade.command)
1015
+ if (command) notes(missing.map(function (key) { return names[key] }).join('、') + ' 侧系统层拦截需要 root:点「提权启动」弹终端输密码,或自行打开终端执行:' + command)
1016
+ if (degrade && degrade.jvmArgs) {
1017
+ notes('降级可用(不经系统层拦截):')
1018
+ notes(' JVM 程序:' + degrade.jvmArgs.join(' '))
1019
+ notes(' 环境变量:ALL_PROXY=' + degrade.httpProxyUrl + ' HTTP_PROXY=' + degrade.httpProxyUrl + ' HTTPS_PROXY=' + degrade.httpProxyUrl)
1020
+ if (degrade.git && degrade.git.host) {
1021
+ notes(' git:已写入 ' + degrade.git.key + ' = ' + degrade.git.value + '(git config --global --get-regexp proxy 可查)')
1022
+ } else if (degrade.socksUrl) {
1023
+ notes(' git:也可执行 git config --global http.<仓库主机>.proxy ' + degrade.socksUrl)
1024
+ }
1025
+ notes(' ' + degrade.note)
1026
+ }
1027
+ }
1028
+ var shortText = ''
1029
+ if (isStray) {
1030
+ pill.className = 'pill err'
1031
+ pill.textContent = '组件不应运行'
1032
+ shortText = '代理引擎已停止,系统层拦截仍在运行'
1033
+ notes('连接会被转发到已关闭的端口;daemon 正在停止它,也可点右侧「停止拦截」。')
1034
+ } else if (!engineRunning) {
1035
+ pill.className = 'pill off'
1036
+ pill.textContent = '代理引擎未启动'
1037
+ shortText = ''
1038
+ } else if (health && health.ok !== true) {
1039
+ var broken = ['linux', 'windows'].filter(function (key) {
1040
+ return sides[key] && sides[key].applicable !== false && sides[key].ok !== true
1041
+ })
1042
+ pill.className = 'pill err'
1043
+ pill.textContent = '组件异常'
1044
+ shortText = broken.length === 0 ? '组件不完整或无法启动' : broken.map(function (key) { return names[key] }).join('、') + ' 侧组件不可用'
1045
+ broken.forEach(function (key) { notes(names[key] + ':' + (sides[key].error || '组件不完整或无法启动')) })
1046
+ } else if (interception.linux !== true && interception.windows !== true) {
1047
+ pill.className = 'pill warn'
1048
+ pill.textContent = '拦截未启动'
1049
+ var idle = ['linux', 'windows'].filter(function (key) {
1050
+ return sides[key] && sides[key].applicable !== false && interception[key] !== true
1051
+ })
1052
+ shortText = idle.length === 0 ? '正在拉起组件' : idle.map(function (key) { return names[key] }).join('、') + ' 侧未运行 · 已降级'
1053
+ planNotes()
1054
+ } else {
1055
+ pill.className = 'pill on'
1056
+ pill.textContent = '拦截运行中'
1057
+ var runningNames = ['linux', 'windows'].filter(function (key) { return interception[key] === true })
1058
+ var idleSides = ['linux', 'windows'].filter(function (key) {
1059
+ return sides[key] && sides[key].applicable !== false && interception[key] !== true
1060
+ })
1061
+ shortText = runningNames.map(function (key) { return names[key] }).join('、') + ' 侧正在拦截'
1062
+ + (idleSides.length === 0 ? '' : '(' + idleSides.map(function (key) { return names[key] }).join('、') + ' 侧未运行 · 已降级)')
1063
+ planNotes()
1064
+ }
1065
+ text.textContent = shortText
1066
+ if (more && detail) {
1067
+ detail.textContent = lines.join('\\n')
1068
+ more.hidden = lines.length === 0
1069
+ }
1070
+ renderElevateNote(health)
1071
+ }
1072
+ // m12606: ask for elevation from the page. sudo is tried first (passwordless),
1073
+ // then pkexec (a real polkit dialog where the desktop has an agent); when neither
1074
+ // can, the banner names the command from 说明 so it can be pasted into a terminal.
1075
+ function elevateBridge() {
1076
+ var button = el('bridge-health-elevate')
1077
+ if (state.elevateBusy === true) return
1078
+ state.elevateBusy = true
1079
+ if (button) { button.disabled = true; button.textContent = '提权中…' }
1080
+ var outcome = { kind: 'warn', text: '' }
1081
+ api('/v1/action', { method: 'POST', body: { action: 'start', cwd: state.cwd } }).then(function (response) {
1082
+ // /v1/action answers {ok, action, result}; the payload is one level down.
1083
+ var result = (response && response.result) || {};
1084
+ var redirector = result.redirector || {};
1085
+ var started = Array.isArray(redirector.started) ? redirector.started : [];
1086
+ var skipped = Array.isArray(redirector.skipped) ? redirector.skipped : [];
1087
+ if (started.length > 0) {
1088
+ outcome = {
1089
+ kind: 'ok',
1090
+ text: '系统层拦截已启动' + (started[0].method === 'pkexec' ? '(经提权窗口)' : ''),
1091
+ side: started[0].side === 'local' ? 'linux' : (started[0].side || ''),
1092
+ }
1093
+ return
1094
+ }
1095
+ // Report the side we were trying to bring up, not a "already running" note
1096
+ // from the side that needed nothing (m12606).
1097
+ var wanted = skipped.filter(function (entry) {
1098
+ return entry && typeof entry.reason === 'string' && entry.reason.indexOf('已在运行') !== 0
1099
+ })
1100
+ var choice = wanted.length > 0 ? wanted[0] : null
1101
+ outcome = {
1102
+ kind: choice !== null && choice.method === 'terminal' ? 'ok' : 'warn',
1103
+ text: choice !== null && typeof choice.reason === 'string'
1104
+ ? choice.reason
1105
+ : '提权没有完成:把「说明」里的命令粘到终端执行,或给 sudo 配置免密',
1106
+ side: choice !== null && choice.side === 'local' ? 'linux' : (choice !== null ? (choice.side || '') : ''),
1107
+ terminal: choice !== null && choice.method === 'terminal',
1108
+ }
1109
+ }).catch(function (error) {
1110
+ outcome = { kind: 'err', text: '提权启动失败:' + error.message }
1111
+ }).then(function () {
1112
+ state.elevateBusy = false
1113
+ if (button) { button.disabled = false; button.textContent = '提权启动' }
1114
+ // The note belongs to the component card, not the rule-table banner (m12923):
1115
+ // a terminal may still be waiting for a password, so the message has to live
1116
+ // next to the component it is about.
1117
+ state.elevateNote = {
1118
+ kind: outcome.kind,
1119
+ text: outcome.text,
1120
+ side: outcome.side || '',
1121
+ at: Date.now(),
1122
+ // A terminal note stays until the helper script removes its state file.
1123
+ terminal: outcome.terminal === true,
1124
+ seenActive: false,
1125
+ }
1126
+ renderElevateNote()
1127
+ Promise.resolve(loadProxyTab())
1128
+ void loadHealth(true)
1129
+ })
1130
+ renderElevateNote()
1131
+ }
1132
+
1133
+ function loadHealth(force) {
1134
+ return api('/v1/proxybridge/health' + (force === true ? '?force=1' : ''))
1135
+ .then(function (health) { renderHealth(health); return health; })
1136
+ .catch(function (error) {
1137
+ var pill = el('bridge-health-pill');
1138
+ if (pill) { pill.className = 'pill warn'; pill.textContent = '检查失败'; }
1139
+ var text = el('bridge-health-text');
1140
+ if (text) text.textContent = error.message;
1141
+ });
1142
+ }
1143
+ function stopStrayBridge() {
1144
+ var stop = el('bridge-health-stop');
1145
+ if (state.stopBusy === true) return;
1146
+ state.stopBusy = true;
1147
+ if (stop) { stop.disabled = true; stop.textContent = '停止中…'; }
1148
+ // api() stringifies body itself; passing a pre-stringified value made the
1149
+ // daemon answer 400, and banner() only RETURNS markup (it is not a setter),
1150
+ // so the failure was silent — the stray-interception self-rescue button did
1151
+ // nothing at all (review C P1-1).
1152
+ api('/v1/action', { method: 'POST', body: { action: 'stop', cwd: state.cwd } })
1153
+ .then(function (response) {
1154
+ var result = (response && response.result) || {}
1155
+ var redirector = result.redirector || {}
1156
+ if (redirector.stopped === false) {
1157
+ var text = el('bridge-health-text')
1158
+ if (text) {
1159
+ text.textContent = '停止拦截未完成:' + (redirector.reason || '未知原因') +
1160
+ (redirector.command ? ';请执行:' + redirector.command : '')
1161
+ }
1162
+ }
1163
+ return loadHealth(true)
1164
+ })
1165
+ .then(function () { return loadProxyTab(); })
1166
+ .catch(function (error) {
1167
+ var text = el('bridge-health-text');
1168
+ if (text) text.textContent = '停止拦截失败:' + error.message;
1169
+ })
1170
+ .finally(function () { state.stopBusy = false; if (stop) { stop.disabled = false; stop.textContent = '停止拦截'; } });
1171
+ }
1172
+ function loadBundle() {
1173
+ return api('/v1/proxybridge').then(function (status) {
1174
+ renderBundle(status);
1175
+ if (status.downloading === true) startBundlePoll();
1176
+ void loadHealth(false);
1177
+ return status;
1178
+ }).catch(function (error) { el('bridge-hint').textContent = error.message; });
1179
+ }
1180
+ function startBundlePoll() {
1181
+ if (bundlePoll !== null) return;
1182
+ bundlePoll = setInterval(function () {
1183
+ api('/v1/proxybridge').then(function (status) {
1184
+ renderBundle(status);
1185
+ if (status.downloading !== true) { clearInterval(bundlePoll); bundlePoll = null; }
1186
+ }).catch(function () { clearInterval(bundlePoll); bundlePoll = null; });
1187
+ }, 1000);
1188
+ }
1189
+ function downloadBundle() {
1190
+ // Reinstalling an existing bundle must not be answered with fromCache without
1191
+ // touching the files: ask the daemon to force the download (the endpoint hands
1192
+ // 'force' to ensureBundle).
1193
+ var force = lastBundleInstalled === true;
1194
+ renderBundle({ downloading: true });
1195
+ // Poll from the start: if the POST itself stalls, the card still follows the
1196
+ // daemon-side download instead of sitting on 「下载中…」 forever.
1197
+ startBundlePoll();
1198
+ return api('/v1/proxybridge/download', { method: 'POST', body: force === true ? { force: true } : {} }).then(function (status) {
1199
+ renderBundle(status);
1200
+ startBundlePoll();
1201
+ // Finished before the first poll (cache hit or a fast mirror).
1202
+ return loadBundle();
1203
+ }).catch(function (error) { renderBundle({ downloading: false, result: { ok: false, error: error.message } }); });
1204
+ }
1205
+ function uploadBundle(file) {
1206
+ if (!file) return;
1207
+ el('bridge-hint').textContent = '正在上传 ' + file.name + '…';
1208
+ return file.arrayBuffer().then(function (bytes) {
1209
+ return fetch('/v1/proxybridge/upload', {
1210
+ method: 'POST',
1211
+ headers: { authorization: 'Bearer ' + TOKEN, 'x-risd-api-version': API_VERSION, 'content-type': 'application/gzip' },
1212
+ body: bytes,
1213
+ }).then(function (res) {
1214
+ return res.json().catch(function () { return {}; }).then(function (body) {
1215
+ if (!res.ok || body.ok === false) throw new Error(body.message || body.error || ('HTTP ' + res.status));
1216
+ return loadBundle();
1217
+ });
1218
+ });
1219
+ }).catch(function (error) { el('bridge-hint').textContent = '上传失败:' + error.message; });
1220
+ }
1221
+
1222
+ // ---- SOCKS reachability chip ----
1223
+ // A wrong SOCKS host/port used to look identical to a healthy one until the first
1224
+ // request failed. The chip probes the upstream every 10 s while the proxy tab is on
1225
+ // screen: green = SOCKS5 greeting answered, amber = the port answered but is not a
1226
+ // usable SOCKS5, red = unreachable (the tooltip says why).
1227
+ function renderPing(result) {
1228
+ var chip = el('proxy-ping');
1229
+ if (!chip) return;
1230
+ var cls = 'pill';
1231
+ var text = '';
1232
+ if (result === null || result === undefined) { cls += ' busy'; text = '检测中…'; }
1233
+ // 没填 SOCKS 地址不是故障:灰色「未配置」,别用红点吓人(review C3-P2-9)。
1234
+ else if (result.configured === false) { cls += ' off'; text = '未配置'; }
1235
+ else if (result.ok === true) { cls += ' on'; text = '连通 ' + ((result.ms || 0) + ' ms'); }
1236
+ else if (result.socks === true) { cls += ' warn'; text = '需认证'; }
1237
+ else { cls += ' err'; text = '无法连接'; }
1238
+ chip.className = cls;
1239
+ chip.textContent = text;
1240
+ chip.title = result === null || result === undefined
1241
+ ? '正在检测代理服务器连通性…'
1242
+ : (result.configured === false
1243
+ ? '还没有填写代理服务器地址'
1244
+ : (result.ok === true ? '代理服务器可达(' + (result.host || '') + ':' + (result.port || '') + ',' + result.at + ')' : String(result.error || '连接失败')));
1245
+ }
1246
+ function refreshPing() {
1247
+ var host = el('proxy-socks-host').value.trim();
1248
+ var port = el('proxy-socks-port').value.trim();
1249
+ var token = state.pingSeq = (state.pingSeq || 0) + 1;
1250
+ // 空地址不发请求:/v1/proxy/ping 必然失败,10 s 一次的必然失败探测没有意义。
1251
+ if (host === '') { renderPing({ configured: false }); return Promise.resolve(null); }
1252
+ renderPing(null);
1253
+ return api('/v1/proxy/ping?host=' + encodeURIComponent(host) + '&port=' + encodeURIComponent(port)).then(function (body) {
1254
+ if (token !== state.pingSeq) return;
1255
+ renderPing(body);
1256
+ }).catch(function (error) {
1257
+ if (token !== state.pingSeq) return;
1258
+ renderPing({ ok: false, socks: false, error: error.message, host: host, port: port });
1259
+ });
1260
+ }
1261
+ function syncPingTimer() {
1262
+ var wanted = state.tab === 'proxy' && document.hidden !== true;
1263
+ if (wanted && state.pingTimer === null) {
1264
+ if (el('proxy-socks-host').value.trim() !== '') refreshPing();
1265
+ state.pingTimer = setInterval(refreshPing, 10000);
1266
+ } else if (!wanted && state.pingTimer !== null) {
1267
+ clearInterval(state.pingTimer);
1268
+ state.pingTimer = null;
1269
+ }
1270
+ }
1271
+
1272
+ // ---- IDE tab ----
1273
+ // One page can drive every workspace: the daemon reports each live dsh window
1274
+ // (cwd + sessionId); the left panel switches between them, and it can collapse
1275
+ // so the iframe gets the whole width.
1276
+ function ideTargetUrl(win) {
1277
+ var base = String(win.url || '');
1278
+ while (base.length > 1 && base.slice(-1) === '/') base = base.slice(0, -1);
1279
+ var cwd = win.cwd || state.cwd || '';
1280
+ return base + '/dsh-ris-ide/window?cwd=' + encodeURIComponent(cwd) +
1281
+ (win.sessionId ? '&sessionId=' + encodeURIComponent(win.sessionId) : '') + '&wname=' + encodeURIComponent(IDE_WNAME);
1282
+ }
1283
+
1284
+ // Collapsed by default (m08228): the IDE needs the width; expand from the header.
1285
+ function sideVisible() { return localStorage.getItem('risd.ideSide') === 'on'; }
1286
+ /** Repaint the sidebar and its header toggle (one control, both states). */
1287
+ function applySide() {
1288
+ var visible = sideVisible();
1289
+ el('ide-side').hidden = !visible;
1290
+ var toggle = el('ide-side-toggle');
1291
+ if (toggle) {
1292
+ toggle.textContent = visible ? '‹' : '›';
1293
+ var label = visible ? '收起工作区面板' : '展开工作区面板';
1294
+ toggle.title = label;
1295
+ toggle.setAttribute('aria-label', label);
1296
+ toggle.setAttribute('aria-expanded', visible ? 'true' : 'false');
1297
+ toggle.disabled = el('view-ide').hidden;
1298
+ }
1299
+ }
1300
+
1301
+ function workspaceBase(cwd) {
1302
+ var parts = String(cwd || '').split('/').filter(Boolean);
1303
+ return parts.length > 0 ? parts[parts.length - 1] : String(cwd || '');
1304
+ }
1305
+ /** A short, stable label: the folder name, with the parent when two collide. */
1306
+ function workspaceLabel(cwd, windows) {
1307
+ var base = workspaceBase(cwd);
1308
+ var same = windows.filter(function (win) { return workspaceBase(win.cwd) === base; }).length;
1309
+ if (same <= 1) return base || '(未知工作区)';
1310
+ var parts = String(cwd || '').split('/').filter(Boolean);
1311
+ return parts.slice(-2).join('/');
1312
+ }
1313
+
1314
+ function focusIdeFrame() {
1315
+ var frame = el('ide-frame');
1316
+ if (frame) { try { frame.focus(); } catch { /* focus is best effort */ } }
1317
+ }
1318
+
1319
+ function selectIdeWindow(windows, cwd) {
1320
+ var win = windows.filter(function (row) { return (row.cwd || '') === cwd; })[0] || windows[0];
1321
+ if (!win) return;
1322
+ var key = win.cwd || '';
1323
+ if (win.live !== false) delete state.staleDismissed[key];
1324
+ var stale = el('ide-stale');
1325
+ if (stale) {
1326
+ stale.hidden = win.live !== false || state.staleDismissed[key] === true;
1327
+ var staleText = el('ide-stale-text');
1328
+ if (staleText) staleText.textContent = '该工作区最近没有活动(dsh 窗口可能已关闭),IDE 仍会尝试加载;若失败请重新打开 dsh 面板。';
1329
+ }
1330
+ if (win.cwd) { state.cwd = win.cwd; localStorage.setItem('risd.cwd', win.cwd); }
1331
+ var frame = ensureIdeFrame();
1332
+ frame.hidden = false;
1333
+ var url = ideTargetUrl(win);
1334
+ // Keep the document alive when the target did not change: switching tabs must
1335
+ // not throw away unsaved edits, the debugger selection or the scroll position
1336
+ // (review C-P0-1).
1337
+ if (frame.getAttribute('src') !== url) frame.src = url;
1338
+ // Move keyboard focus into the embedded IDE: cross-origin iframes receive their
1339
+ // own key events natively, but only while they hold focus. This also runs when
1340
+ // the document was reused (workspace switch), where Ctrl+F must stay inside.
1341
+ try { frame.focus(); } catch { /* focus is best effort */ }
1342
+ el('ide-ws-list').querySelectorAll('[data-cwd]').forEach(function (button) {
1343
+ button.classList.toggle('active', button.getAttribute('data-cwd') === (win.cwd || ''));
1344
+ });
1345
+ }
1346
+
1347
+ function ensureIdeFrame() {
1348
+ var frame = el('ide-frame');
1349
+ if (frame) return frame;
1350
+ frame = document.createElement('iframe');
1351
+ frame.id = 'ide-frame';
1352
+ frame.className = 'ide-frame';
1353
+ frame.title = 'RIS-IDE';
1354
+ el('ide-body').appendChild(frame);
1355
+ return frame;
1356
+ }
1357
+
1358
+ function ideMessage(kind, text, note) {
1359
+ var box = el('ide-msg');
1360
+ box.hidden = false;
1361
+ box.innerHTML = banner(kind, text) + (note ? '<p class="note">' + esc(note) + '</p>' : '');
1362
+ }
1363
+
1364
+ function clearIdeMessage() {
1365
+ var box = el('ide-msg');
1366
+ if (box) {
1367
+ box.hidden = true;
1368
+ box.innerHTML = '';
1369
+ }
1370
+ }
1371
+
1372
+ function renderIde(windows, current) {
1373
+ var selected = current || windows[0];
1374
+ el('ide-ws-list').innerHTML = windows.map(function (win) {
1375
+ var label = workspaceLabel(win.cwd, windows);
1376
+ // Non-live entries stay clickable: dsh may still have the session, the iframe
1377
+ // shows the real result (m08268).
1378
+ var suffix = win.live === false ? '(未活跃)' : '';
1379
+ return '<li><button type="button" data-cwd="' + esc(win.cwd || '') + '" title="' + esc((win.cwd || '') + (suffix ? ' ' + suffix : '')) + '">' +
1380
+ esc(label + suffix) + '</button></li>';
1381
+ }).join('');
1382
+ var staleClose = el('ide-stale-close');
1383
+ if (staleClose) {
1384
+ staleClose.onclick = function () {
1385
+ state.staleDismissed[state.cwd || ''] = true;
1386
+ var bar = el('ide-stale');
1387
+ if (bar) bar.hidden = true;
1388
+ };
1389
+ }
1390
+
1391
+ el('ide-ws-list').onclick = function (event) {
1392
+ var button = event.target.closest('[data-cwd]');
1393
+ if (button) selectIdeWindow(windows, button.getAttribute('data-cwd'));
1394
+ };
1395
+ clearIdeMessage();
1396
+ ensureIdeFrame();
1397
+ applySide();
1398
+ selectIdeWindow(windows, selected.cwd || '');
1399
+ }
1400
+
1401
+ function ideUnavailable(body) {
1402
+ el('ide-ws-list').innerHTML = '';
1403
+ var frame = el('ide-frame');
1404
+ if (frame) frame.hidden = true;
1405
+ ideMessage('warn', 'IDE 不可用:' + (body.reason || 'dsh 未运行'),
1406
+ 'IDE 界面由 dsh 提供;启动 dsh 并打开一次 RIS-IDE 面板后,这里会自动可用。');
1407
+ applySide();
1408
+ }
1409
+
1410
+ function loadIde() {
1411
+ if (!el('ide-frame') && el('ide-msg').hidden) {
1412
+ el('ide-msg').hidden = false;
1413
+ el('ide-msg').innerHTML = '<p class="empty">检查 dsh 状态…</p>';
1414
+ }
1415
+ return api('/v1/dsh').then(function (body) {
1416
+ state.dsh = body;
1417
+ state.dshSignature = dshWindowSignature(body);
1418
+ var windows = body.windows || [];
1419
+ if (!body.available || windows.length === 0) {
1420
+ ideUnavailable(body);
1421
+ return;
1422
+ }
1423
+ var preferred = state.cwd;
1424
+ var selected = windows.filter(function (win) { return (win.cwd || '') === preferred; })[0] ||
1425
+ windows.filter(function (win) { return win.live !== false; })[0] || windows[0];
1426
+ renderIde(windows, selected);
1427
+ }).catch(function (error) {
1428
+ ideMessage('err', 'IDE 状态读取失败:' + error.message);
1429
+ });
1430
+ }
1431
+
1432
+ /**
1433
+ * Re-read the window list but keep the existing iframe: called when the IDE tab
1434
+ * is re-opened or the dsh window set changed. Rebuilding the element here was
1435
+ * the P0 that silently dropped unsaved edits.
1436
+ */
1437
+ function refreshIdeWindows() {
1438
+ return api('/v1/dsh').then(function (body) {
1439
+ state.dsh = body;
1440
+ state.dshSignature = dshWindowSignature(body);
1441
+ var windows = body.windows || [];
1442
+ if (!body.available || windows.length === 0) {
1443
+ ideUnavailable(body);
1444
+ return;
1445
+ }
1446
+ var preferred = state.cwd;
1447
+ var selected = windows.filter(function (win) { return (win.cwd || '') === preferred; })[0] ||
1448
+ windows.filter(function (win) { return win.live !== false; })[0] || windows[0];
1449
+ renderIde(windows, selected);
1450
+ }).catch(function (error) {
1451
+ ideMessage('err', 'IDE 状态读取失败:' + error.message);
1452
+ });
1453
+ }
1454
+
1455
+ function dshWindowSignature(body) {
1456
+ // Liveness is part of the rendering state: a window going 未活跃 must repaint
1457
+ // the hint bar even though cwd/sessionId did not change.
1458
+ return (body.windows || []).map(function (win) {
1459
+ return (win.cwd || '') + '|' + (win.sessionId || '') + '|' + (win.live === false ? 'stale' : 'live');
1460
+ }).sort().join('\\n');
1461
+ }
1462
+
1463
+ /** Grey the IDE tab when no dsh window is answering; re-check every 5s. */
1464
+ function syncDshTab() {
1465
+ return api('/v1/dsh').then(function (body) {
1466
+ var available = body.available === true && (body.windows || []).length > 0;
1467
+ var changed = state.dshAvailable !== available;
1468
+ state.dsh = body;
1469
+ state.dshAvailable = available;
1470
+ var tab = document.querySelector('nav button[data-tab="ide"]');
1471
+ tab.disabled = !available;
1472
+ tab.title = available
1473
+ ? '嵌入 dsh 的 IDE(可按工作区切换)'
1474
+ : ('IDE 不可用:' + (body.reason || 'dsh 未运行'));
1475
+ var signature = dshWindowSignature(body);
1476
+ var windowsChanged = state.dshSignature !== signature;
1477
+ state.dshSignature = signature;
1478
+ if (state.tab === 'ide' && (changed || windowsChanged)) {
1479
+ if (available) refreshIdeWindows();
1480
+ else ideUnavailable(body);
1481
+ }
1482
+ return available;
1483
+ }).catch(function () {
1484
+ state.dshAvailable = false;
1485
+ var tab = document.querySelector('nav button[data-tab="ide"]');
1486
+ tab.disabled = true;
1487
+ tab.title = 'IDE 不可用:无法读取 dsh 状态';
1488
+ return false;
1489
+ });
1490
+ }
1491
+
1492
+ // ---- tabs ----
1493
+ function showTab(name) {
1494
+ // Refuse a disabled IDE tab BEFORE touching visibility: the old order made the
1495
+ // pane visible and then returned, so any caller other than a click (deep link,
1496
+ // shortcut) would leave an empty IDE view behind (review C-P2-9).
1497
+ if (name === 'ide') {
1498
+ var ideTab = document.querySelector('nav button[data-tab="ide"]');
1499
+ if (ideTab && ideTab.disabled) return;
1500
+ }
1501
+ state.tab = name;
1502
+ try { localStorage.setItem(TAB_STORAGE, name); } catch { /* storage off */ }
1503
+ document.querySelectorAll('nav button[data-tab]').forEach(function (button) {
1504
+ button.setAttribute('aria-selected', button.getAttribute('data-tab') === name ? 'true' : 'false');
1505
+ });
1506
+ el('view-overview').hidden = name !== 'overview';
1507
+ el('view-proxy').hidden = name !== 'proxy';
1508
+ el('view-ide').hidden = name !== 'ide';
1509
+ if (name === 'overview') refreshOverview();
1510
+ if (name === 'proxy') loadProxyTab();
1511
+ // Re-opening the tab must not reload the embedded IDE: only the window list is
1512
+ // refreshed, the iframe (and its unsaved state) stays (review C-P0-1).
1513
+ if (name === 'ide') { if (el('ide-frame')) refreshIdeWindows(); else loadIde(); }
1514
+ // Leaving the proxy tab must stop the log tail; entering it restarts it only if
1515
+ // the pane was already on (review C-P2-3).
1516
+ syncLogTimer();
1517
+ // Same lifecycle for the reachability chip: never probe while another tab shows.
1518
+ syncPingTimer();
1519
+ syncHealthTimer();
1520
+ // The header toggle only applies to the IDE pane: disable it (with its title
1521
+ // explaining why) while another tab is showing.
1522
+ applySide();
1523
+ }
1524
+
1525
+ // ---- wiring ----
1526
+ document.querySelectorAll('nav button[data-tab]').forEach(function (button) {
1527
+ button.onclick = function () { showTab(button.getAttribute('data-tab')); };
1528
+ });
1529
+ // Stopping the daemon stops everything it supervises, so it gets a real
1530
+ // reminder (not a one-line confirm): list what is about to go away.
1531
+ function askStopDaemon() {
1532
+ return refreshOverview().catch(function () {}).then(function () {
1533
+ var summary = state.summary || {};
1534
+ var programs = summary.programs || 0;
1535
+ var debugs = summary.debugs || 0;
1536
+ var lines = [];
1537
+ lines.push('停止后需要重新启动 dsh,或手跑 <b>risd serve</b>,才能再次使用代理与 IDE。');
1538
+ lines.push('将要停止:');
1539
+ lines.push('· 代理引擎:' + (summary.proxyRunning ? '<b>运行中</b>(会一并停止)' : '未运行'));
1540
+ lines.push('· 系统层拦截:随代理一起拆除(可能弹一次提权确认)');
1541
+ lines.push('· 运行中的项目:<b>' + programs + '</b> 个' + (programs > 0 ? '(会先停止)' : ''));
1542
+ lines.push('· 调试会话:<b>' + debugs + '</b> 个' + (debugs > 0 ? '(会先断开)' : ''));
1543
+ el('confirm-body').innerHTML = lines.join('<br>');
1544
+ el('confirm').hidden = false;
1545
+ return new Promise(function (resolve) {
1546
+ function finish(value) {
1547
+ el('confirm').hidden = true;
1548
+ el('confirm-ok').onclick = null;
1549
+ el('confirm-cancel').onclick = null;
1550
+ document.removeEventListener('keydown', onKey);
1551
+ resolve(value);
1552
+ }
1553
+ function onKey(event) { if (event.key === 'Escape') finish(false); }
1554
+ el('confirm-ok').onclick = function () { finish(true); };
1555
+ el('confirm-cancel').onclick = function () { finish(false); };
1556
+ document.addEventListener('keydown', onKey);
1557
+ });
1558
+ });
1559
+ }
1560
+ el('daemon-stop').onclick = function () {
1561
+ askStopDaemon().then(function (ok) {
1562
+ if (!ok) return;
1563
+ return shutdownDaemon();
1564
+ });
1565
+ };
1566
+ // (overview's 停止 keeps its own path below; the proxy tab's stop reloads the tab.)
1567
+ function shutdownDaemon() {
1568
+ api('/v1/shutdown', { method: 'POST', body: {} }).catch(function () { /* the page dies with it */ });
1569
+ el('daemon-pill').className = 'pill off';
1570
+ el('daemon-pill').textContent = '已停止';
1571
+ el('daemon-sub').textContent = '页面已断开;下次 daemonMode=auto 的 dsh 启动或手跑 risd serve 会重新拉起';
1572
+ };
1573
+ // One button, two states: the label IS the next action (m10585). A stop leaves it
1574
+ // reading 启动, so the same spot brings the tunnel back. Starting can wait seconds
1575
+ // behind sudo/UAC, so both buttons show the in-flight action and ignore clicks
1576
+ // until it settles (user m11279).
1577
+ var engineBusy = false;
1578
+ var engineBusyAction = '';
1579
+ function paintEngineButtons() {
1580
+ var running = state.summary.proxyRunning === true || state.proxyRunning === true;
1581
+ [el('engine-toggle'), el('proxy-engine-toggle')].forEach(function (button) {
1582
+ if (!button) return;
1583
+ if (engineBusy) {
1584
+ button.disabled = true;
1585
+ button.setAttribute('aria-busy', 'true');
1586
+ button.textContent = engineBusyAction === 'stop' ? '停止中…' : '启动中…';
1587
+ return;
1588
+ }
1589
+ button.removeAttribute('aria-busy');
1590
+ button.disabled = false;
1591
+ button.textContent = running ? '停止' : '启动';
1592
+ button.className = running ? 'danger' : '';
1593
+ button.title = running
1594
+ ? '停止引擎、系统层拦截与 git 代理'
1595
+ : '按当前规则表启动代理引擎(系统层拦截可能需要提权)';
1596
+ });
1597
+ }
1598
+ function toggleProxyEngine() {
1599
+ if (engineBusy) return;
1600
+ var running = state.summary.proxyRunning === true || state.proxyRunning === true;
1601
+ var action = running ? 'stop' : 'start';
1602
+ var host = state.tab === 'proxy' ? el('proxy-banner') : el('overview-banner');
1603
+ host.innerHTML = '';
1604
+ engineBusy = true;
1605
+ engineBusyAction = action;
1606
+ paintEngineButtons();
1607
+ api('/v1/action', { method: 'POST', body: { action: action, cwd: state.cwd } })
1608
+ .then(function (response) {
1609
+ var result = (response && response.result) || {};
1610
+ var redirector = result.redirector || {};
1611
+ var skipped = Array.isArray(redirector.skipped) ? redirector.skipped : [];
1612
+ engineBusy = false;
1613
+ paintEngineButtons();
1614
+ // Write the elevation warning AFTER the refresh: loadProxyTab empties
1615
+ // #proxy-banner, so a message written before it vanished in the same frame
1616
+ // (评审 20261109-2326 客户端 P2). maybeStartProxy already orders it so.
1617
+ // A stop that the OS refused (root-owned CLI) or that lost a race with
1618
+ // an in-flight start must not look like a clean stop (review B-P1-2/B-P1-5).
1619
+ var stopBlocked = action === 'stop' && redirector.stopped === false
1620
+ var warn = stopBlocked
1621
+ ? '系统层拦截未完全停止:' + (redirector.reason || '未知原因') +
1622
+ (redirector.command ? ';请执行:' + redirector.command : '')
1623
+ : skipped.length > 0
1624
+ ? '本机引擎已启动;系统层拦截需要提权:' + skipped.map(function (item) { return item.side + ':' + item.reason; }).join(';')
1625
+ : '';
1626
+ return (state.tab === 'proxy'
1627
+ ? loadProxyTab().then(function () { return loadHealth(true); })
1628
+ : refreshOverview().then(function () { return loadHealth(true); })
1629
+ ).then(function () {
1630
+ if (warn !== '') host.innerHTML = banner('warn', warn);
1631
+ });
1632
+ })
1633
+ .catch(function (error) {
1634
+ engineBusy = false;
1635
+ paintEngineButtons();
1636
+ host.innerHTML = banner('err', (running ? '停止' : '启动') + '代理引擎失败:' + error.message +
1637
+ (running ? '(可以再点一次重试;仍不行就停掉守护进程,它会一并拆除引擎)' : ''));
1638
+ });
1639
+ }
1640
+ el('engine-toggle').onclick = toggleProxyEngine;
1641
+ el('proxy-engine-toggle').onclick = toggleProxyEngine;
1642
+ el('bridge-health-stop').onclick = stopStrayBridge;
1643
+ el('bridge-health-elevate').onclick = elevateBridge;
1644
+ el('lifecycle-save').onclick = saveLifecycle;
1645
+ // Any toggle means "this form is mine now": the 4 s refresh stops refilling it
1646
+ // until the save succeeds (review C-P2-3).
1647
+ el('lifecycle-rows').addEventListener('change', function () { state.lifecycleDirty = true; });
1648
+
1649
+ // Re-probe while the user edits host/port: 800 ms after the last keystroke, and
1650
+ // only on the proxy tab (the inputs are hidden elsewhere).
1651
+ var pingDebounce = null;
1652
+ function queuePing() {
1653
+ if (state.tab !== 'proxy') return;
1654
+ if (pingDebounce !== null) clearTimeout(pingDebounce);
1655
+ pingDebounce = setTimeout(function () { pingDebounce = null; refreshPing(); }, 800);
1656
+ }
1657
+ el('proxy-socks-host').addEventListener('input', queuePing);
1658
+ el('proxy-socks-port').addEventListener('input', queuePing);
1659
+ // Dirty tracking: the proxy tab is the only editable form on this page, and a
1660
+ // drift-banner refresh must not silently throw the edit away (review C3 P1-3).
1661
+ // Editing is the save: every change (socks 行/端口/规则表) re-validates and, once
1662
+ // the form is complete, writes the table and starts the engine if it was down.
1663
+ el('proxy-socks-host').addEventListener('input', scheduleProxySave);
1664
+ el('proxy-socks-port').addEventListener('input', scheduleProxySave);
1665
+ el('proxy-listen').addEventListener('input', scheduleProxySave);
1666
+ el('proxy-rules').addEventListener('input', scheduleProxySave);
1667
+ el('proxy-rules').addEventListener('change', scheduleProxySave);
1668
+ el('proxy-add').onclick = function () {
1669
+ var rules = (state.view && state.view.rules ? state.view.rules.slice() : []);
1670
+ rules.push({ id: 'user-' + Math.random().toString(36).slice(2, 9), program: '', hosts: '', ports: '*', enabled: true, source: 'user', shadow: false });
1671
+ renderProxyTab(Object.assign({}, state.view || {}, { rules: rules }));
1672
+ scheduleProxySave();
1673
+ };
1674
+ el('bridge-restart').onclick = function () {
1675
+ api('/v1/action', { method: 'POST', body: { action: 'redirector-restart', cwd: state.cwd } })
1676
+ .then(function (response) {
1677
+ // The action result lives under result: reading response.started always
1678
+ // found nothing and reported "需要提权" even after a successful restart
1679
+ // (review C-P1-3).
1680
+ var result = (response && response.result) || {};
1681
+ var skipped = Array.isArray(result.skipped) ? result.skipped : [];
1682
+ var started = Array.isArray(result.started) ? result.started : [];
1683
+ var text = started.length > 0
1684
+ ? '已按新规则重启(' + started.join(',') + ')'
1685
+ : '需要提权:' + JSON.stringify(skipped.length > 0 ? skipped : (result.stopped || {}));
1686
+ el('proxy-banner').innerHTML = banner(started.length > 0 ? 'ok' : 'warn', text);
1687
+ }).catch(function (error) { el('proxy-banner').innerHTML = banner('err', error.message); });
1688
+ };
1689
+ el('bridge-download').onclick = downloadBundle;
1690
+ el('bridge-upload').onclick = function () { el('bridge-file').click(); };
1691
+ el('bridge-file').onchange = function (event) {
1692
+ var file = event.target.files && event.target.files[0];
1693
+ uploadBundle(file);
1694
+ event.target.value = '';
1695
+ };
1696
+ el('proxy-log-toggle').onclick = logToggle;
1697
+ el('proxy-rules').onclick = function (event) {
1698
+ var remove = event.target.getAttribute('data-remove');
1699
+ if (remove === null) return;
1700
+ var rules = rulesFromTable();
1701
+ rules.splice(Number(remove), 1);
1702
+ renderProxyTab(Object.assign({}, state.view || {}, { rules: rules }));
1703
+ // Deleting is an edit like any other: schedule the write, otherwise the table on
1704
+ // screen and the table the engine uses diverge until the next keystroke.
1705
+ scheduleProxySave();
1706
+ };
1707
+ el('projects').onclick = function (event) {
1708
+ var button = event.target.closest('[data-stop-program]');
1709
+ if (!button) return;
1710
+ var cwd = button.getAttribute('data-cwd');
1711
+ var id = button.getAttribute('data-stop-program');
1712
+ api('/v1/programs', { method: 'POST', body: { cwd: cwd, action: 'stop', id: id } })
1713
+ .then(loadProjects).catch(function (error) { alert(error.message); });
1714
+ };
1715
+ el('debugs').onclick = function (event) {
1716
+ var stop = event.target.closest('[data-stop-debug]');
1717
+ if (stop) {
1718
+ api('/v1/debug', { method: 'POST', body: { action: 'stop', cwd: stop.getAttribute('data-cwd'), id: stop.getAttribute('data-stop-debug') } })
1719
+ .then(loadDebugs).catch(function (error) { alert(error.message); });
1720
+ return;
1721
+ }
1722
+ var forget = event.target.closest('[data-forget-debug]');
1723
+ if (forget) {
1724
+ if (!window.confirm('清除这条调试记录?断点集合也会一起丢失。')) return;
1725
+ api('/v1/debug', { method: 'POST', body: { action: 'forget', logPath: forget.getAttribute('data-forget-debug') } })
1726
+ .then(loadDebugs).catch(function (error) { alert(error.message); });
1727
+ return;
1728
+ }
1729
+ var detach = event.target.closest('[data-detach]');
1730
+ if (!detach) return;
1731
+ api('/v1/debug', { method: 'POST', body: { action: 'detach', logPath: detach.getAttribute('data-detach') } })
1732
+ .then(loadDebugs).catch(function (error) { alert(error.message); });
1733
+ };
1734
+
1735
+ // Which tab to open: an explicit ?tab= wins (handy for tests/docs), a plain
1736
+ // entry (the dsh ⧉ deep-links with only ?cwd=, m11345) and a reload both fall
1737
+ // back to the tab the user was last on (m10900). Same for the workspace:
1738
+ // showTab/selectIdeWindow write localStorage, so a shortcut- or toolbar reload
1739
+ // keeps both.
1740
+ var TAB_STORAGE = 'risd.tab';
1741
+ var requestedTab = 'overview';
1742
+ try {
1743
+ var wanted = new URLSearchParams(location.search).get('tab');
1744
+ if (wanted === 'ide' || wanted === 'proxy' || wanted === 'overview') {
1745
+ requestedTab = wanted;
1746
+ } else {
1747
+ var savedTab = localStorage.getItem(TAB_STORAGE);
1748
+ if (savedTab === 'ide' || savedTab === 'proxy' || savedTab === 'overview') requestedTab = savedTab;
1749
+ }
1750
+ } catch { /* no URL API / no storage */ }
1751
+ el('ide-side-toggle').onclick = function () {
1752
+ localStorage.setItem('risd.ideSide', sideVisible() ? 'off' : 'on');
1753
+ applySide();
1754
+ };
1755
+ // Clicking anywhere outside the iframe puts the caret back into the embedded
1756
+ // IDE. A cross-origin iframe swallows clicks inside itself, so any click that
1757
+ // reaches this document means the user left the IDE: refocus it. (Clicks on the
1758
+ // workspace list run first; focus moves after the switch has been applied.)
1759
+ document.addEventListener('click', function (event) {
1760
+ if (state.tab !== 'ide') return;
1761
+ var frame = el('ide-frame');
1762
+ if (!frame || event.target === frame) return;
1763
+ focusIdeFrame();
1764
+ }, true);
1765
+ applySide();
1766
+ // Coming back to the tab must resume the log tail immediately, and hiding the
1767
+ // page must stop it (review C-P2-3).
1768
+ document.addEventListener('visibilitychange', function () { syncLogTimer(); syncPingTimer(); syncHealthTimer(); });
1769
+
1770
+ // ---- 页面代码漂移 / 令牌漂移(m09693、review C3-P1-3)----
1771
+ // 以前 loaded 变化直接 location.reload():代理规则表正在编辑时刷新会丢失输入,
1772
+ // 内嵌 IDE iframe 的 beforeunload 在跨源页面里还不弹。现在只提示,刷新由用户点。
1773
+ function showDrift(text, mode) {
1774
+ var box = el('ui-drift');
1775
+ if (!box) return;
1776
+ var message = String(text || '');
1777
+ if (message !== '' && message === driftDismissedFor) return;
1778
+ driftMessage = message;
1779
+ driftMode = mode === 'restart' ? 'restart' : 'reload';
1780
+ var label = el('ui-drift-text');
1781
+ if (label) label.textContent = message;
1782
+ var button = el('ui-drift-reload');
1783
+ if (button) {
1784
+ button.disabled = false;
1785
+ button.textContent = driftMode === 'restart' ? '重启并刷新' : '刷新';
1786
+ button.title = driftMode === 'restart' ? '先重启 daemon,再重新加载本页' : '重新加载本页';
1787
+ }
1788
+ box.hidden = false;
1789
+ }
1790
+ function hideDrift() {
1791
+ var box = el('ui-drift');
1792
+ if (box) box.hidden = true;
1793
+ }
1794
+ // The embedded IDE lives in a cross-origin iframe, so the only way to know
1795
+ // whether a reload would drop unsaved editor buffers is to ask it over
1796
+ // postMessage (m10900). The iframe answers only its own parent (see
1797
+ // lib/client.js), and a frame that predates the bridge simply does not answer
1798
+ // — treated as "unknown", which never triggers an automatic reload.
1799
+ var ideAskState = { seq: 0, waiting: {} };
1800
+ function ideFrameWindow() {
1801
+ var frame = el('ide-frame');
1802
+ if (!frame) return null;
1803
+ try { return frame.contentWindow; } catch { return null; }
1804
+ }
1805
+ function askIdeDirty() {
1806
+ var target = ideFrameWindow();
1807
+ if (target === null) return Promise.resolve(0);
1808
+ var requestId = 'dirty-' + (ideAskState.seq += 1);
1809
+ return new Promise(function (resolve) {
1810
+ var timer = setTimeout(function () {
1811
+ delete ideAskState.waiting[requestId];
1812
+ resolve(null);
1813
+ }, 1500);
1814
+ ideAskState.waiting[requestId] = { resolve: resolve, timer: timer };
1815
+ try {
1816
+ target.postMessage({ type: 'dsh-ris-ide:probe-dirty', requestId: requestId }, '*');
1817
+ } catch {
1818
+ clearTimeout(timer);
1819
+ delete ideAskState.waiting[requestId];
1820
+ resolve(null);
1821
+ }
1822
+ }).then(function (data) {
1823
+ if (data === null || typeof data.count !== 'number') return null;
1824
+ return data.count;
1825
+ });
1826
+ }
1827
+ function askIdeSaveAll() {
1828
+ var target = ideFrameWindow();
1829
+ if (target === null) return Promise.resolve(false);
1830
+ var requestId = 'save-' + (ideAskState.seq += 1);
1831
+ return new Promise(function (resolve) {
1832
+ var timer = setTimeout(function () {
1833
+ delete ideAskState.waiting[requestId];
1834
+ resolve(null);
1835
+ }, 20000);
1836
+ ideAskState.waiting[requestId] = { resolve: resolve, timer: timer };
1837
+ try {
1838
+ target.postMessage({ type: 'dsh-ris-ide:save-all', requestId: requestId }, '*');
1839
+ } catch {
1840
+ clearTimeout(timer);
1841
+ delete ideAskState.waiting[requestId];
1842
+ resolve(null);
1843
+ }
1844
+ }).then(function (data) { return data !== null && data.ok === true; });
1845
+ }
1846
+ window.addEventListener('message', function (event) {
1847
+ var data = event.data;
1848
+ if (data === null || typeof data !== 'object') return;
1849
+ if (data.type !== 'dsh-ris-ide:dirty-report' && data.type !== 'dsh-ris-ide:save-all-done') return;
1850
+ var pending = ideAskState.waiting[data.requestId];
1851
+ if (pending === undefined) return;
1852
+ delete ideAskState.waiting[data.requestId];
1853
+ clearTimeout(pending.timer);
1854
+ pending.resolve(data);
1855
+ });
1856
+
1857
+ // The drift bar can offer a save-all when the embedded IDE holds drafts: a
1858
+ // reload would otherwise silently drop them (the iframe's beforeunload does
1859
+ // not run for a cross-origin reload).
1860
+ function setDriftSave(count) {
1861
+ var button = el('ui-drift-save');
1862
+ if (!button) return;
1863
+ button.hidden = !(typeof count === 'number' && count > 0);
1864
+ button.disabled = false;
1865
+ button.textContent = '保存所有文件';
1866
+ }
1867
+ function driftSaveThenReload() {
1868
+ // The drift bar reloads on behalf of a newer bundle: it needs the same
1869
+ // unsaved-work checks as the ordinary refresh button, otherwise the rule table
1870
+ // or the lifecycle checkboxes are silently thrown away (评审 20261109-2326
1871
+ // 客户端 P2).
1872
+ if (state.proxyDirty === true && window.confirm('代理规则还没保存,刷新会丢失') !== true) return
1873
+ if (state.lifecycleDirty === true && window.confirm('生命周期设置还没保存,刷新会丢失') !== true) return
1874
+ var button = el('ui-drift-save');
1875
+ if (button) { button.disabled = true; button.textContent = '保存中…'; }
1876
+ askIdeSaveAll().then(function (saved) {
1877
+ if (saved !== true) {
1878
+ if (button) { button.disabled = false; button.textContent = '保存所有文件'; }
1879
+ showDrift('有文件没保存成功:先在开发环境里处理,再点「重启并刷新」', driftMode);
1880
+ return;
1881
+ }
1882
+ if (driftMode === 'restart') { restartDaemon(); return; }
1883
+ location.reload();
1884
+ });
1885
+ }
1886
+ // m11421: 插件版本更新后,旧 daemon 进程里 import 过的模块不会变,光刷新页面
1887
+ // 只会再拿到一份旧代码。这里让 daemon 自己交接重启(保留代理引擎),等新 instance
1888
+ // 出现在免认证的 /v1/health 上,再刷新本页。
1889
+ function restartDaemon() {
1890
+ var button = el('ui-drift-reload');
1891
+ if (button) { button.disabled = true; button.textContent = '重启中…'; }
1892
+ var previous = PAGE_INSTANCE;
1893
+ showDrift('插件版本已更新:正在重启 daemon,完成后本页会自动刷新…', 'restart');
1894
+ api('/v1/restart', { method: 'POST' }).catch(function () { /* 进程退出会切断这个请求,属正常 */ });
1895
+ var startedAt = Date.now();
1896
+ var timer = setInterval(function () {
1897
+ if (Date.now() - startedAt > 30000) {
1898
+ clearInterval(timer);
1899
+ showDrift('插件版本已更新,但 daemon 重启超时:手动重启后刷新本页', 'restart');
1900
+ if (button) { button.disabled = false; button.textContent = '重启并刷新'; }
1901
+ return;
1902
+ }
1903
+ fetch('/v1/health', { headers: { 'x-risd-api-version': '1' } })
1904
+ .then(function (res) { return res.json(); })
1905
+ .then(function (body) {
1906
+ if (body && body.ok === true && body.instance && body.instance !== previous) {
1907
+ clearInterval(timer);
1908
+ location.reload();
1909
+ }
1910
+ })
1911
+ .catch(function () { /* daemon 还没起来,下一轮再看 */ });
1912
+ }, 400);
1913
+ }
1914
+ function restartDaemonThenReload() {
1915
+ if (state.proxyDirty === true && window.confirm('代理规则还没保存,重启并刷新会丢失') !== true) return;
1916
+ if (state.lifecycleDirty === true && window.confirm('生命周期设置还没保存,重启并刷新会丢失') !== true) return;
1917
+ askIdeDirty().then(function (count) {
1918
+ if (count === 0) { restartDaemon(); return; }
1919
+ setDriftSave(count);
1920
+ if (count === null) showDrift('无法确认开发环境里有没有未保存的文件:先保存,再点「重启并刷新」', 'restart');
1921
+ else showDrift('开发环境里有 ' + count + ' 个文件未保存:先点「保存所有文件」,再点「重启并刷新」', 'restart');
1922
+ });
1923
+ }
1924
+ function reloadPage() {
1925
+ // Unsaved proxy rules are the only edit on THIS page worth a confirm; the IDE
1926
+ // buffers are discovered through the bridge and turned into the save-all button.
1927
+ if (state.proxyDirty === true && window.confirm('代理规则还没保存,刷新会丢失') !== true) return;
1928
+ askIdeDirty().then(function (count) {
1929
+ if (count === 0) { location.reload(); return; }
1930
+ setDriftSave(count);
1931
+ if (count === null) showDrift('无法确认开发环境里有没有未保存的文件,刷新前请先保存');
1932
+ else showDrift('开发环境里有 ' + count + ' 个文件未保存:先点「保存所有文件」,再刷新');
1933
+ });
1934
+ }
1935
+ if (el('ui-drift-reload')) el('ui-drift-reload').addEventListener('click', function () {
1936
+ if (driftMode === 'restart') restartDaemonThenReload();
1937
+ else reloadPage();
1938
+ });
1939
+ if (el('ui-drift-save')) el('ui-drift-save').addEventListener('click', driftSaveThenReload);
1940
+ if (el('ui-drift-close')) {
1941
+ el('ui-drift-close').addEventListener('click', function () { driftDismissedFor = driftMessage; hideDrift(); });
1942
+ }
1943
+ function checkBuild() {
1944
+ return api('/v1/health').then(function (body) {
1945
+ if (!body) return;
1946
+ // A different instance = a restarted daemon: every token on this page is dead
1947
+ // and the HTML is stale. Reloading is the only cure — automatically when that
1948
+ // cannot lose work, otherwise with the button (the old page is unusable either
1949
+ // way: the daemon rejects its token).
1950
+ var stale = (PAGE_INSTANCE && body.instance && body.instance !== PAGE_INSTANCE)
1951
+ || (PAGE_BUILD && body.uiBuild && body.uiBuild.loaded && body.uiBuild.loaded !== PAGE_BUILD);
1952
+ if (stale) {
1953
+ return askIdeDirty().then(function (count) {
1954
+ var safe = count === 0 && state.proxyDirty !== true && state.lifecycleDirty !== true;
1955
+ if (safe) { location.reload(); return; }
1956
+ setDriftSave(count);
1957
+ if (count === null) showDrift('daemon 已重启:本页令牌已失效;无法确认开发环境里有没有未保存的文件,刷新前请先保存');
1958
+ else if (count > 0) showDrift('daemon 已重启:本页令牌已失效;开发环境里有 ' + count + ' 个文件未保存,先点「保存所有文件」');
1959
+ else showDrift('daemon 已重启:本页令牌已失效,点右侧「刷新」');
1960
+ });
1961
+ }
1962
+ var build = body.uiBuild ? body.uiBuild : null;
1963
+ if (build === null) { hideDrift(); return; }
1964
+ // disk≠loaded = 源码比进程新:刷新拿不到新代码,只能提示重启 daemon。
1965
+ if (build.disk && build.loaded && build.disk !== build.loaded) {
1966
+ showDrift('插件版本已更新,点「重启并刷新」后生效', 'restart');
1967
+ return;
1968
+ }
1969
+ hideDrift();
1970
+ }).catch(function () { /* daemon 忙/重启中:下一轮再看 */ });
1971
+ }
1972
+ state.buildTimer = setInterval(function () { if (!document.hidden) checkBuild(); }, 5000);
1973
+ void checkBuild();
1974
+ syncDshTab().then(function (available) {
1975
+ // A dsh click asks for the IDE tab; without a live dsh fall back to 概览.
1976
+ showTab(requestedTab === 'ide' && available !== true ? 'overview' : requestedTab);
1977
+ });
1978
+ state.pollTimer = setInterval(function () {
1979
+ if (document.hidden) return;
1980
+ // The window list feeds the IDE tab and the overview's daemon row; reading it
1981
+ // from the proxy tab was wasted work (review C-P2-3).
1982
+ if (state.tab === 'ide' || state.tab === 'overview') syncDshTab();
1983
+ if (state.tab === 'overview') refreshOverview();
1984
+ }, 4000);
1985
+ })();
1986
+ </script>
1987
+ </body>
1988
+ </html>`
1989
+ }