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/client.js CHANGED
@@ -110,6 +110,123 @@ window.__ModuleLoader__.load({
110
110
  return typeof window !== 'undefined' && window.__dshRisIdeWindow === true
111
111
  }
112
112
 
113
+ /**
114
+ * The client bundle this page is running, as the host told us when the page
115
+ * booted. `null` until the first hello/build answer (see `watchClientBuild`).
116
+ */
117
+ var pageBuildId = null
118
+ var buildWatcherInstalled = false
119
+ /** How often an open page re-asks the host which bundle it serves. */
120
+ var BUILD_POLL_MS = 30000
121
+ /** The build a hint was raised for, and the one the user closed it for. */
122
+ var staleNoticeBuild = null
123
+ var staleNoticeDismissedFor = null
124
+
125
+ /**
126
+ * Tell the user that the IDE code changed under the open page.
127
+ *
128
+ * Neither page shape reloads itself: the standalone window owns an editor that
129
+ * can hold unsaved buffers, and a DSH page would drop the conversation view. The
130
+ * bar carries the refresh button and is idempotent — later hellos/focus polls
131
+ * reuse the same node instead of stacking bars.
132
+ * @param {string} build - the build id the hint is for.
133
+ */
134
+ function showStaleBuildNotice(build) {
135
+ staleNoticeBuild = typeof build === 'string' ? build : null
136
+ if (typeof document === 'undefined') return
137
+ var existing = document.getElementById('dsh-ris-ide-build-stale')
138
+ if (existing !== null) { existing.hidden = false; return }
139
+ var bar = document.createElement('div')
140
+ bar.id = 'dsh-ris-ide-build-stale'
141
+ bar.setAttribute('role', 'status')
142
+ bar.style.cssText = 'position:fixed;right:16px;bottom:16px;z-index:2147483000;display:flex;align-items:center;gap:10px;'
143
+ + 'padding:8px 12px;border-radius:8px;background:#eef4ff;border:1px solid #d7e4ff;color:#1d4ed8;'
144
+ + 'font:13px/1.4 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang SC","Microsoft YaHei",sans-serif;'
145
+ + 'box-shadow:0 6px 20px rgba(15,23,42,.12)'
146
+ var text = document.createElement('span')
147
+ text.textContent = 'IDE 界面已更新:刷新页面后生效'
148
+ var reload = document.createElement('button')
149
+ reload.type = 'button'
150
+ reload.textContent = '刷新'
151
+ reload.style.cssText = 'border:1px solid #bcd3ff;background:#fff;color:#1d4ed8;border-radius:6px;padding:2px 10px;cursor:pointer;font:inherit'
152
+ reload.addEventListener('click', function () { location.reload() })
153
+ var close = document.createElement('button')
154
+ close.type = 'button'
155
+ close.textContent = '×'
156
+ close.title = '关闭提示'
157
+ close.setAttribute('aria-label', '关闭提示')
158
+ close.style.cssText = 'border:0;background:transparent;color:inherit;cursor:pointer;font:inherit;padding:0 2px'
159
+ close.addEventListener('click', function () {
160
+ // Remember which build was dismissed: the 30s poll must not re-open the bar
161
+ // for the same stale bundle, but a NEWER build still has to warn.
162
+ staleNoticeDismissedFor = staleNoticeBuild
163
+ bar.hidden = true
164
+ })
165
+ bar.appendChild(text)
166
+ bar.appendChild(reload)
167
+ bar.appendChild(close)
168
+ document.body.appendChild(bar)
169
+ }
170
+
171
+ /**
172
+ * Keep this page on the client bundle the host is serving.
173
+ *
174
+ * Plugin bundles are served with `immutable` caching and a revision-baked URL,
175
+ * so a reload already gets the new build — the stale thing is the ALREADY OPEN
176
+ * page, which keeps executing the bundle it booted. The host stamps the build
177
+ * into the stream's hello and serves it at `/dsh-ris-ide/build`; this watcher
178
+ * takes the first answer as "what this page runs" and, when a later answer
179
+ * differs, raises the refresh hint. It never reloads by itself, and it keeps
180
+ * `pageBuildId` on the bundle this page actually runs, so a cancelled or missed
181
+ * reload keeps the hint up (review C3-P1-2).
182
+ *
183
+ * Rides the existing stream hub for the push case, plus a slow visibility-aware
184
+ * poll for pages that stay in the foreground (a hello only arrives when the
185
+ * stream (re)connects). A hub that is not connected yet is fine — the first
186
+ * answer becomes the baseline.
187
+ */
188
+ function watchClientBuild() {
189
+ if (buildWatcherInstalled || typeof window === 'undefined') return
190
+ // A real browser page always has EventSource; a Node test harness that imports
191
+ // this file does not, and must not start a stream (or a fetch to a relative
192
+ // URL, or a timer) just because `apply` ran — that surfaced as an async
193
+ // "EventSource is not defined" after the test had already ended.
194
+ if (typeof EventSource !== 'function') return
195
+ buildWatcherInstalled = true
196
+ function note(build) {
197
+ if (typeof build !== 'string' || build === '') return
198
+ if (pageBuildId === null) { pageBuildId = build; return }
199
+ if (build === pageBuildId) return
200
+ // A dismissed hint stays dismissed for THAT build; a newer bundle re-warns.
201
+ if (build === staleNoticeDismissedFor) return
202
+ showStaleBuildNotice(build)
203
+ }
204
+ function pollBuild() {
205
+ if (typeof document !== 'undefined' && document.hidden === true) return
206
+ void fetch(routeUrl('dsh-ris-ide/build').href, { headers: { accept: 'application/json' } })
207
+ .then(function (response) { return response.ok === true ? response.json() : null })
208
+ .then(function (body) { if (body !== null && body !== undefined) note(body.build) })
209
+ .catch(function () { /* host unreachable: keep the build we already know */ })
210
+ }
211
+ try {
212
+ var hub = risStreamHub()
213
+ hub.subscribe({
214
+ topics: ['hello'],
215
+ handlers: {
216
+ hello: function (payload) {
217
+ if (payload === null || payload === undefined || payload.ok !== true) return
218
+ note(payload.build)
219
+ },
220
+ },
221
+ })
222
+ } catch { /* no hub (old host): the fetch below still seeds the baseline */ }
223
+ // Seed the baseline even when the stream is not up yet, so a page opened
224
+ // before the first hello can still notice the change.
225
+ pollBuild()
226
+ setInterval(pollBuild, BUILD_POLL_MS)
227
+ if (typeof window.addEventListener === 'function') window.addEventListener('focus', pollBuild)
228
+ }
229
+
113
230
  /** Point the RIS-IDE tab at one program (consumed by the panel). */
114
231
  function selectProgram(program) {
115
232
  pendingProgram = program === null || program === undefined ? null : program
@@ -1094,7 +1211,12 @@ window.__ModuleLoader__.load({
1094
1211
  }
1095
1212
  }
1096
1213
 
1097
- /** Storage key + default height of the compact panel's log pane. */
1214
+ /**
1215
+ * Storage key + default height of the compact panel's log pane.
1216
+ * Deliberately NOT workspace-scoped (unlike the IDE tabs/recent list): the
1217
+ * compact layout is a preference of this machine, and two panes of the same
1218
+ * page should agree on how tall the log is (评审 20261109-2326 客户端 P2).
1219
+ */
1098
1220
  var COMPACT_UI_KEY = 'dsh-ris-ide:ui:compact'
1099
1221
  var COMPACT_PANE_DEFAULT = 240
1100
1222
 
@@ -1110,7 +1232,10 @@ window.__ModuleLoader__.load({
1110
1232
  return Math.min(Math.max(120, value), 720)
1111
1233
  }
1112
1234
 
1113
- /** Storage key of the compact panel's maximized section ('' | 'console' | 'log'). */
1235
+ /**
1236
+ * Storage key of the compact panel's maximized section ('' | 'console' | 'log').
1237
+ * Machine-wide on purpose, same as COMPACT_UI_KEY above.
1238
+ */
1114
1239
  var COMPACT_MAX_KEY = 'dsh-ris-ide:ui:compact-max'
1115
1240
 
1116
1241
  /**
@@ -1906,1074 +2031,6 @@ window.__ModuleLoader__.load({
1906
2031
  * Editing is local until 保存: the engine keeps its listeners until restarted,
1907
2032
  * so the dialog says so out loud instead of pretending a save took effect.
1908
2033
  */
1909
- function ProxyDialog(props) {
1910
- var scope = props && typeof props.scope === 'object' && props.scope !== null ? props.scope : {}
1911
- var sessionId = typeof scope.sessionId === 'string' ? scope.sessionId : ''
1912
- var cwd = typeof scope.cwd === 'string' ? scope.cwd : ''
1913
- var onClose = props && typeof props.onClose === 'function' ? props.onClose : function () {}
1914
- var [state, setState] = useState({
1915
- loading: true, error: '', note: '', view: null, draft: null, pickFor: '', pickFilter: '', busy: '',
1916
- // Auto-save runs on its own flag: a background write must not disable the
1917
- // 启动/停止 buttons, and it must not look like a manual action either.
1918
- saving: false,
1919
- // Command handed back by the redirector action when this route cannot
1920
- // elevate: it is shown verbatim so the user can paste it in a terminal.
1921
- redirectorCommand: '',
1922
- })
1923
- var [programs, setPrograms] = useState([])
1924
- var [programsLoaded, setProgramsLoaded] = useState(false)
1925
- // Two sources for a rule's 程序 field: a process that is running NOW, or a
1926
- // fixed executable picked from disk (configure it before the program ever
1927
- // starts, so it is proxied from its first connection).
1928
- // Three sources for the 程序 field: a process running NOW, a file on this
1929
- // (Linux/WSL) side, a file on the Windows side. The two file sources are the
1930
- // only way to configure a program that never runs as a child of this pane.
1931
- var [pickMode, setPickMode] = useState('running')
1932
- // ONE tree per dialog, lazily filled: `nodes[path] = {dirs, files, error}`.
1933
- // Expanding a folder reads just that folder, so a huge drive never has to be
1934
- // walked up front, and the tree keeps its shape while it grows in place.
1935
- var [tree, setTree] = useState({ side: 'local', roots: null, nodes: {}, expanded: {}, loading: {}, error: '' })
1936
-
1937
- /**
1938
- * Read ONE directory into the tree (roots when `target` is '').
1939
- *
1940
- * Called lazily: when a folder is first expanded, and when a side is first
1941
- * shown. Everything already read stays cached for the life of the dialog, so
1942
- * collapsing and re-expanding costs nothing.
1943
- */
1944
- function loadTreeDir(target, sideOverride) {
1945
- var side = typeof sideOverride === 'string' && sideOverride !== '' ? sideOverride : tree.side
1946
- var key = typeof target === 'string' ? target : ''
1947
- setTree(function (prev) {
1948
- var loading = Object.assign({}, prev.loading)
1949
- loading[key] = true
1950
- return Object.assign({}, prev, { loading: loading, error: '' })
1951
- })
1952
- var url = routeUrl('/dsh-ris-ide/proxy/browse')
1953
- url.searchParams.set('sessionId', sessionId)
1954
- if (cwd !== '') url.searchParams.set('cwd', cwd)
1955
- url.searchParams.set('side', side)
1956
- if (key !== '') url.searchParams.set('path', key)
1957
- return fetch(url.href, { headers: { accept: 'application/json' } })
1958
- .then(function (response) { return response.json() })
1959
- .then(function (payload) {
1960
- if (payload.ok !== true) throw new Error(payload.message || '读取目录失败')
1961
- setTree(function (prev) {
1962
- var nodes = Object.assign({}, prev.nodes)
1963
- nodes[payload.path] = { dirs: payload.dirs || [], files: payload.files || [] }
1964
- var loading = Object.assign({}, prev.loading)
1965
- delete loading[key]
1966
- return Object.assign({}, prev, {
1967
- side: payload.side === 'windows' ? 'windows' : 'local',
1968
- // The roots are only known from the first answer: they are the quick
1969
- // entry points (workspace / home / temp / drives).
1970
- roots: prev.roots === null ? (payload.roots || []) : prev.roots,
1971
- nodes: nodes,
1972
- loading: loading,
1973
- error: '',
1974
- })
1975
- })
1976
- })
1977
- .catch(function (error) {
1978
- setTree(function (prev) {
1979
- var loading = Object.assign({}, prev.loading)
1980
- delete loading[key]
1981
- return Object.assign({}, prev, { loading: loading, error: String(error && error.message ? error.message : error) })
1982
- })
1983
- })
1984
- }
1985
-
1986
- /** Toggle a folder open/closed, reading it the first time. */
1987
- function toggleDir(dir) {
1988
- var key = dir.path
1989
- var known = tree.nodes[key]
1990
- if (known !== undefined && known.dirs.length === 0 && known.files.length === 0) return
1991
- var open = tree.expanded[key] === true
1992
- setTree(function (prev) {
1993
- var expanded = Object.assign({}, prev.expanded)
1994
- if (open) delete expanded[key]
1995
- else expanded[key] = true
1996
- return Object.assign({}, prev, { expanded: expanded })
1997
- })
1998
- if (open !== true && tree.nodes[key] === undefined) void loadTreeDir(key)
1999
- }
2000
-
2001
- // Fingerprint of the table the form was rendered from: it travels with every
2002
- // write, so another window's save is detected instead of being overwritten.
2003
- var revisionRef = useRef('')
2004
-
2005
- /**
2006
- * The editable form shape for one host view.
2007
- *
2008
- * Two callers need it: the first read and the 409 reload (another window saved
2009
- * first). Keeping one mapper means both produce the SAME folded fields, so the
2010
- * dialog compares like with like when it decides whether a write is needed.
2011
- */
2012
- function draftFromView(payload) {
2013
- return {
2014
- socks: {
2015
- host: payload.socks && payload.socks.host ? payload.socks.host : '',
2016
- port: payload.socks && payload.socks.port ? String(payload.socks.port) : '',
2017
- },
2018
- listenPort: String(payload.listenPort || ''),
2019
- rules: (Array.isArray(payload.rules) ? payload.rules : []).map(function (rule) {
2020
- return {
2021
- id: rule.id, program: rule.program, hosts: rule.hosts || '', ports: rule.ports || '',
2022
- enabled: rule.enabled === true, shadow: rule.shadow === true, source: rule.source,
2023
- shadowable: rule.shadowable === true, hostsInvalid: rule.hostsInvalid || [], portsInvalid: rule.portsInvalid || [],
2024
- socksCapable: rule.socksCapable === true, autoShadow: rule.autoShadow === true, workspace: rule.workspace || '',
2025
- // Whether the rule's own program is up (started from this row).
2026
- run: rule.run || null, runLogPath: rule.runLogPath || '',
2027
- // Host-derived facts, so the row shows what the ENGINE concluded instead
2028
- // of recomputing it here and drifting from the host's answer.
2029
- // A starter row: shown, but not written until the user actually changes it.
2030
- template: rule.template === true,
2031
- effective: rule.effective === true, ineffectiveReason: String(rule.ineffectiveReason || ''),
2032
- portsParsed: Array.isArray(rule.portsParsed) ? rule.portsParsed : [],
2033
- }
2034
- }),
2035
- }
2036
- }
2037
-
2038
- /** Close the dialog, but never throw away a write that is still debounced. */
2039
- function closeDialog() {
2040
- flushSave().catch(function () {}).then(function () { onClose() })
2041
- }
2042
-
2043
- /** GET the stored rules; `draft` is what the form edits. */
2044
- function load() {
2045
- setState(function (prev) { return Object.assign({}, prev, { loading: true, error: '' }) })
2046
- var url = routeUrl('/dsh-ris-ide/proxy')
2047
- url.searchParams.set('sessionId', sessionId)
2048
- if (cwd !== '') url.searchParams.set('cwd', cwd)
2049
- return fetch(url.href, { headers: { accept: 'application/json' } })
2050
- .then(function (response) {
2051
- // A 404 here means the host half of this plugin is older than the
2052
- // client half (the page reloads from disk, the host only on restart).
2053
- if (response.ok !== true) throw new Error('读取代理配置失败:HTTP ' + String(response.status) + (response.status === 404 ? '(dsh-ris-ide 宿主未加载该路由,需重启 dsh web)' : ''))
2054
- return response.json()
2055
- })
2056
- .then(function (payload) {
2057
- if (payload.ok !== true) throw new Error(payload.message || '读取代理配置失败')
2058
- var draft = draftFromView(payload)
2059
- // Remember the loaded shape: without this the first render would look
2060
- // like an edit and auto-save the file back onto itself.
2061
- savedSignature.current = draftSignature(draft)
2062
- revisionRef.current = typeof payload.revision === 'string' ? payload.revision : ''
2063
- var ids = {}
2064
- payload.rules.forEach(function (rule) { ids[rule.id] = true })
2065
- savedIds.current = ids
2066
- setState(function (prev) { return Object.assign({}, prev, { loading: false, view: payload, draft: draft }) })
2067
- })
2068
- .catch(function (error) { setState(function (prev) { return Object.assign({}, prev, { loading: false, error: String(error && error.message ? error.message : error) }) }) })
2069
- }
2070
-
2071
- useEffect(function () { load() }, [sessionId, cwd])
2072
- /**
2073
- * The running-process list is only needed once the picker opens (it costs a
2074
- * PowerShell round trip on Windows), so it is fetched lazily and then cached.
2075
- */
2076
- function loadPrograms(force) {
2077
- if (programsLoaded === true && force !== true) return Promise.resolve()
2078
- var url = routeUrl('/dsh-ris-ide/proxy/programs')
2079
- url.searchParams.set('sessionId', sessionId)
2080
- if (cwd !== '') url.searchParams.set('cwd', cwd)
2081
- return fetch(url.href, { headers: { accept: 'application/json' } })
2082
- .then(function (response) { return response.json() })
2083
- .then(function (payload) {
2084
- if (payload && payload.ok === true && Array.isArray(payload.programs)) {
2085
- setPrograms(payload.programs)
2086
- setProgramsLoaded(true)
2087
- }
2088
- })
2089
- .catch(function () { /* the picker falls back to free text */ })
2090
- }
2091
-
2092
- /** Patch one rule of the draft (by id). */
2093
- function patchRule(id, patch) {
2094
- setState(function (prev) {
2095
- if (prev.draft === null) return prev
2096
- // Editing a starter row is what turns it into a stored rule: until then it
2097
- // is only a suggestion the host re-derives on every read.
2098
- var rules = prev.draft.rules.map(function (rule) {
2099
- return rule.id === id ? Object.assign({}, rule, patch, { template: false }) : rule
2100
- })
2101
- return Object.assign({}, prev, { draft: Object.assign({}, prev.draft, { rules: rules }) })
2102
- })
2103
- }
2104
-
2105
- /** Add one blank rule for the user to fill in. */
2106
- function addRule() {
2107
- setState(function (prev) {
2108
- if (prev.draft === null) return prev
2109
- var id = 'r' + Date.now().toString(36)
2110
- var rules = prev.draft.rules.concat([{ id: id, program: '', hosts: '', ports: '', enabled: true, shadow: false, source: 'user', workspace: cwd }])
2111
- // Just the row: the program cell is editable and has its own 选… button,
2112
- // so opening the picker here would cover the table the user just added to.
2113
- return Object.assign({}, prev, { draft: Object.assign({}, prev.draft, { rules: rules }) })
2114
- })
2115
- }
2116
-
2117
- /**
2118
- * Whether this program can take the SOCKS address directly, so the mapping
2119
- * checkbox can say what it is for: `java`/`git`/`node`/`curl` do not need
2120
- * it, a JDBC/Navicat-style client cannot work without it.
2121
- */
2122
- var SOCKS_CAPABLE = ['java', 'javaw', 'mvn', 'gradle', 'node', 'npm', 'npx', 'git', 'curl', 'python', 'python3', 'bash', 'sh', 'zsh']
2123
-
2124
- function programBasename(program) {
2125
- var text = String(program || '').replace(/\\/g, '/')
2126
- var base = text.split('/').pop() || ''
2127
- return base.trim().toLowerCase().replace(/\.(exe|cmd|bat|sh)$/, '')
2128
- }
2129
-
2130
- function programSpeaksSocks(program) {
2131
- return SOCKS_CAPABLE.indexOf(programBasename(program)) !== -1
2132
- }
2133
-
2134
- /**
2135
- * Recompute what this draft row can do without asking the host: which
2136
- * fragments parse, whether a loopback port can be bound (literal IPv4 +
2137
- * explicit ports), and whether the program needs one at all.
2138
- */
2139
- function parseRuleSpec(rule) {
2140
- var hosts = String(rule.hosts || '').split(',').map(function (part) { return part.trim() }).filter(Boolean)
2141
- var hostsInvalid = hosts.filter(function (part) { return !/^[A-Za-z0-9*]([A-Za-z0-9.*_-]*[A-Za-z0-9*])?$/.test(part) })
2142
- var literal = hosts.length > 0 && hosts.every(function (part) { return /^\d{1,3}(\.\d{1,3}){3}$/.test(part) })
2143
- var ports = []
2144
- var portsInvalid = []
2145
- var portsAny = false
2146
- String(rule.ports || '').split(',').forEach(function (part) {
2147
- var text = part.trim()
2148
- if (text === '') return
2149
- // `*` = every port; a blank spec is NOT that (the rule would not apply).
2150
- if (text === '*') { portsAny = true; return }
2151
- // The host's grammar, not a second dialect: `1000 - 1003` is a range there.
2152
- var range = /^(\d{1,5})\s*-\s*(\d{1,5})$/.exec(text)
2153
- if (range !== null) {
2154
- var from = Number(range[1])
2155
- var to = Number(range[2])
2156
- if (from >= 1 && to <= 65535 && from <= to) { for (var port = from; port <= to; port += 1) ports.push(port) } else portsInvalid.push(text)
2157
- return
2158
- }
2159
- var value = Number(text)
2160
- if (Number.isInteger(value) && value >= 1 && value <= 65535) ports.push(value)
2161
- else portsInvalid.push(text)
2162
- })
2163
- // `*` means "any port" (0) and cannot be bound, so it never makes a row shadowable.
2164
- var bindable = ports.filter(function (port) { return port > 0 })
2165
- var shadowable = literal && bindable.length > 0
2166
- var speaksSocks = programSpeaksSocks(rule.program)
2167
- // Same rule as the host: enabled + program + IP + port, all explicit
2168
- // (`*` = everything). A blank axis means "does not apply", shown in the row.
2169
- var program = String(rule.program || '').trim()
2170
- var verdict = { effective: true, reason: '' }
2171
- if (rule.enabled !== true) verdict = { effective: false, reason: '未启用' }
2172
- else if (program === '') verdict = { effective: false, reason: '缺程序' }
2173
- else if (hosts.length === 0) verdict = { effective: false, reason: '缺 IP(全匹配写 *)' }
2174
- else if (hostsInvalid.length > 0) verdict = { effective: false, reason: 'IP 有无效片段' }
2175
- else if (ports.length === 0 && portsAny !== true) verdict = { effective: false, reason: '缺端口(全匹配写 *)' }
2176
- else if (portsInvalid.length > 0) verdict = { effective: false, reason: '端口有无效片段' }
2177
- return {
2178
- hosts: rule.hosts, ports: rule.ports,
2179
- hostsInvalid: hostsInvalid, portsInvalid: portsInvalid,
2180
- shadowable: shadowable,
2181
- socksCapable: speaksSocks,
2182
- effective: verdict.effective,
2183
- ineffectiveReason: verdict.reason,
2184
- autoShadow: shadowable && !speaksSocks,
2185
- shadow: rule.shadow === true && shadowable ? true : (rule.shadow === false ? false : shadowable && !speaksSocks),
2186
- }
2187
- }
2188
-
2189
- /** Drop a rule (the auto rows are re-added by the host, so this is safe). */
2190
- function dropRule(id) {
2191
- setState(function (prev) {
2192
- if (prev.draft === null) return prev
2193
- return Object.assign({}, prev, { draft: Object.assign({}, prev.draft, { rules: prev.draft.rules.filter(function (rule) { return rule.id !== id }) }), pickFor: '' })
2194
- })
2195
- }
2196
-
2197
- /** POST the draft; the host normalises it and answers the parse diagnostics. */
2198
- /**
2199
- * What the form currently says, in one comparable string.
2200
- *
2201
- * The dialog has no 保存 button: every edit is written automatically, so it
2202
- * needs a cheap way to tell "the user changed something" from "this is just
2203
- * the echo of my own write".
2204
- */
2205
- function draftSignature(draft) {
2206
- if (draft === null) return ''
2207
- return JSON.stringify({
2208
- socks: [String(draft.socks.host).trim(), String(draft.socks.port).trim()],
2209
- listenPort: String(draft.listenPort).trim(),
2210
- rules: draft.rules.map(function (rule) {
2211
- return [rule.id, String(rule.program).trim(), rule.hosts, rule.ports, rule.enabled === true, rule.shadow === true, rule.source]
2212
- }),
2213
- })
2214
- }
2215
- // Signature of what the host last confirmed. A write that comes back identical
2216
- // must not schedule another write, or the dialog would loop forever.
2217
- var savedSignature = useRef('')
2218
- // Rule ids that exist on disk right now: a NEW half-typed row is simply not
2219
- // written, while a SAVED row edited into a half-typed state must not keep its
2220
- // old content silently — it is written as disabled instead.
2221
- var savedIds = useRef({})
2222
- // The 700 ms debounce means an edit can still be in flight when the dialog
2223
- // closes or a button is pressed; both paths must write first, or the reload
2224
- // that follows silently throws the edit away.
2225
- var saveTimer = useRef(null)
2226
-
2227
- /** Write now if the form differs from what the host confirmed. */
2228
- function flushSave() {
2229
- if (saveTimer.current !== null) { clearTimeout(saveTimer.current); saveTimer.current = null }
2230
- if (state.draft === null) return Promise.resolve()
2231
- if (draftSignature(state.draft) === savedSignature.current) return Promise.resolve()
2232
- return save()
2233
- }
2234
-
2235
- /**
2236
- * Rows that are half-typed do not go to disk.
2237
- *
2238
- * Auto-save fires while the user is still typing, so a rule with no program or
2239
- * no port would otherwise be written as a broken row and come back as a rule
2240
- * that silently does nothing. A DISABLED row is kept: that is a decision, not
2241
- * an unfinished edit.
2242
- */
2243
- function storableRule(rule) {
2244
- var spec = parseRuleSpec(rule)
2245
- if (String(rule.program || '').trim() === '') return false
2246
- if (String(rule.hosts || '').trim() === '') return false
2247
- if (String(rule.ports || '').trim() === '') return false
2248
- if (spec.hostsInvalid.length > 0) return false
2249
- if (spec.portsInvalid.length > 0) return false
2250
- return true
2251
- }
2252
-
2253
- /**
2254
- * What to write for one row: `write` (complete), `disable` (a row that is
2255
- * already on disk was edited into an incomplete state) or `skip` (a brand new
2256
- * row that is still being typed).
2257
- */
2258
- function writeMode(rule) {
2259
- if (storableRule(rule)) return 'write'
2260
- return savedIds.current[rule.id] === true ? 'disable' : 'skip'
2261
- }
2262
-
2263
- function save() {
2264
- if (state.draft === null) return
2265
- var skipped = 0
2266
- var disabledByEdit = 0
2267
- var storable = []
2268
- state.draft.rules.forEach(function (rule) {
2269
- // Starter rows are re-derived from AUTO_PROGRAMS on every read: writing one
2270
- // would freeze today's suggestion into the machine-wide table forever.
2271
- if (rule.template === true) return
2272
- var mode = writeMode(rule)
2273
- if (mode === 'skip') { skipped += 1; return }
2274
- if (mode === 'disable') { disabledByEdit += 1; storable.push(Object.assign({}, rule, { enabled: false })); return }
2275
- storable.push(rule)
2276
- })
2277
- // Nothing writable at all (every row is a new row still being typed): keep
2278
- // what is on disk instead of writing an empty table over it.
2279
- if (storable.length === 0 && skipped > 0) {
2280
- setState(function (prev) { return Object.assign({}, prev, { saving: false, note: '规则还没填完整,暂不写入(' + skipped + ' 条待补全)' }) })
2281
- return Promise.resolve()
2282
- }
2283
- var body = {
2284
- sessionId: sessionId,
2285
- cwd: cwd,
2286
- // What the form was rendered from: a mismatch means someone else saved first.
2287
- revision: revisionRef.current,
2288
- config: {
2289
- socks: { host: state.draft.socks.host.trim(), port: Number(state.draft.socks.port) || 0 },
2290
- listenPort: Number(state.draft.listenPort) || 0,
2291
- rules: storable.map(function (rule) {
2292
- return { id: rule.id, program: rule.program.trim(), hosts: rule.hosts, ports: rule.ports, enabled: rule.enabled, shadow: rule.shadow, source: rule.source, workspace: cwd }
2293
- }),
2294
- },
2295
- }
2296
- var signature = draftSignature(state.draft)
2297
- setState(function (prev) { return Object.assign({}, prev, { saving: true, error: '' }) })
2298
- return fetch(routeUrl('/dsh-ris-ide/proxy').href, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
2299
- .then(function (response) { return response.json().then(function (payload) { return { status: response.status, payload: payload } }) })
2300
- .then(function (answer) {
2301
- var payload = answer.payload
2302
- if (answer.status === 409 && payload.conflict === true) {
2303
- // Reload instead of retrying: the other window's rows are the truth now,
2304
- // and the user's own pending edit is gone from disk — say so plainly.
2305
- revisionRef.current = typeof payload.revision === 'string' ? payload.revision : ''
2306
- var fresh = payload.view && Array.isArray(payload.view.rules) ? draftFromView(payload.view) : null
2307
- setState(function (prev) {
2308
- return Object.assign({}, prev, {
2309
- saving: false,
2310
- view: payload.view || prev.view,
2311
- draft: fresh === null ? prev.draft : fresh,
2312
- note: '规则表已在别处被修改,已重新载入(本次改动未写入)',
2313
- error: '',
2314
- })
2315
- })
2316
- if (fresh !== null) {
2317
- savedSignature.current = draftSignature(fresh)
2318
- var conflictIds = {}
2319
- fresh.rules.forEach(function (rule) { conflictIds[rule.id] = true })
2320
- savedIds.current = conflictIds
2321
- }
2322
- return
2323
- }
2324
- if (payload.ok !== true) throw new Error(payload.message || '保存失败')
2325
- revisionRef.current = typeof payload.revision === 'string' ? payload.revision : ''
2326
- savedSignature.current = signature
2327
- var ids = {}
2328
- ;(payload.rules || []).forEach(function (rule) { ids[rule.id] = true })
2329
- savedIds.current = ids
2330
- var note = (payload.reloadNote ? '已自动保存 · ' + payload.reloadNote : '已自动保存,本机引擎已实时应用')
2331
- + (skipped > 0 ? '(' + skipped + ' 条未填完整,未写入)' : '')
2332
- + (disabledByEdit > 0 ? '(' + disabledByEdit + ' 条改到一半,已置为停用)' : '')
2333
- setState(function (prev) { return Object.assign({}, prev, { saving: false, note: note, view: payload }) })
2334
- })
2335
- .catch(function (error) { setState(function (prev) { return Object.assign({}, prev, { saving: false, error: String(error && error.message ? error.message : error) }) }) })
2336
- }
2337
-
2338
- // Write 700ms after the last edit: typing an IP should produce one write, not
2339
- // one per keystroke (each write may also reload the system-level interceptor).
2340
- useEffect(function () {
2341
- if (state.draft === null) return undefined
2342
- var signature = draftSignature(state.draft)
2343
- if (signature === savedSignature.current) return undefined
2344
- saveTimer.current = setTimeout(function () { saveTimer.current = null; void save() }, 700)
2345
- return function () {
2346
- if (saveTimer.current !== null) { clearTimeout(saveTimer.current); saveTimer.current = null }
2347
- }
2348
- }, [state.draft])
2349
-
2350
- /**
2351
- * start / stop / git-on / git-off, then refresh the view.
2352
- * `ruleId` is only used by run/run-stop (the per-row 启动/停止 button).
2353
- */
2354
- function act(action, ruleId, side) {
2355
- // The action reloads the whole view; a pending auto-save must land first or
2356
- // the reload would overwrite the edit and it would never reach the disk.
2357
- flushSave().catch(function () {}).then(function () { actNow(action, ruleId, side) })
2358
- }
2359
-
2360
- function actNow(action, ruleId, side) {
2361
- setState(function (prev) { return Object.assign({}, prev, { busy: action, error: '', note: '' }) })
2362
- fetch(routeUrl('/dsh-ris-ide/proxy/action').href, {
2363
- method: 'POST',
2364
- headers: { 'content-type': 'application/json' },
2365
- body: JSON.stringify({ sessionId: sessionId, cwd: cwd, action: action, ruleId: ruleId, side: side }),
2366
- })
2367
- .then(function (response) { return response.json() })
2368
- .then(function (payload) {
2369
- if (payload.ok !== true) throw new Error(payload.message || '操作失败')
2370
- var result = payload.result || {}
2371
- var redirectorCommand = typeof result.command === 'object' && result.command !== null && typeof result.command.display === 'string'
2372
- ? result.command.display
2373
- : (action === 'redirector-stop' ? '' : state.redirectorCommand)
2374
- // The redirector rides along with start/stop, so its outcome is part of
2375
- // the note: a UAC prompt that was dismissed must not look like success.
2376
- var bridgeNote = ''
2377
- var bridge = result.redirector
2378
- if (bridge !== undefined && bridge !== null && typeof bridge === 'object') {
2379
- var started = Array.isArray(bridge.started) ? bridge.started : []
2380
- var skipped = Array.isArray(bridge.skipped) ? bridge.skipped : []
2381
- if (action === 'start') {
2382
- bridgeNote = started.length > 0
2383
- ? ' · 系统层拦截已启动(' + started.map(function (item) { return item.side }).join('+') + ')'
2384
- : (skipped.length > 0 && skipped[0].reason !== undefined ? ' · 系统层拦截:' + String(skipped[0].reason) : '')
2385
- } else if (action === 'stop') {
2386
- bridgeNote = bridge.stopped === true ? ' · 系统层拦截已停止' : ''
2387
- }
2388
- }
2389
- var gitNote = ''
2390
- if (result.git !== undefined && result.git !== null && typeof result.git === 'object') {
2391
- if (action === 'start') {
2392
- gitNote = result.git.ok === true && result.git.key !== ''
2393
- ? ' · git 代理已写入 ' + String(result.git.key)
2394
- : (result.git.error !== undefined ? ' · git:' + String(result.git.error) : '')
2395
- } else if (action === 'stop' && result.git.key !== undefined && result.git.key !== '') {
2396
- gitNote = ' · git 代理已清除'
2397
- }
2398
- }
2399
- var note = action === 'start'
2400
- ? (result.ok === true ? '已启动:' + (payload.socksUrl || '') + bridgeNote + gitNote : String(result.error || '启动失败'))
2401
- : action === 'stop'
2402
- ? (result.ok === true ? '已停止' + bridgeNote + gitNote : String(result.error || '停止失败'))
2403
- : action === 'git-on' || action === 'git-off'
2404
- ? (result.ok === true ? 'git 配置 ' + String(result.key || '') + (action === 'git-on' ? ' 已写入' : ' 已清除') : String(result.error || 'git 配置失败'))
2405
- : action === 'redirector-sync'
2406
- ? '配置已导出' + (result.reason ? ':' + String(result.reason) : '')
2407
- : action === 'redirector-start'
2408
- ? (result.started === true
2409
- ? '系统层拦截已启动(pid ' + String(result.pid || '') + ')'
2410
- : '未能启动' + (result.reason ? ':' + String(result.reason) : '') + '(命令见下方)')
2411
- : action === 'redirector-stop'
2412
- ? (result.stopped === true ? '系统层拦截已停止' : '未能停止' + (result.reason ? ':' + String(result.reason) : ''))
2413
- : ''
2414
- return load().then(function () {
2415
- setState(function (prev) { return Object.assign({}, prev, { busy: '', note: note, redirectorCommand: redirectorCommand }) })
2416
- })
2417
- })
2418
- .catch(function (error) { setState(function (prev) { return Object.assign({}, prev, { busy: '', error: String(error && error.message ? error.message : error) }) }) })
2419
- }
2420
-
2421
- var draft = state.draft
2422
- var view = state.view
2423
- // `fontFamily: 'inherit'` is load-bearing: a form control does NOT inherit the
2424
- // page font, so without it the dialog's inputs and buttons render in the
2425
- // browser's UI font and the sidebar shape still wraps rows.
2426
- var field = { width: '100%', boxSizing: 'border-box', fontFamily: 'inherit', fontSize: 12, padding: '3px 6px', borderRadius: 4, border: '1px solid color-mix(in srgb, currentColor 22%, transparent)', background: 'transparent', color: 'inherit' }
2427
- var tiny = { fontSize: 11, opacity: 0.62 }
2428
- /** One labelled input of the address section. */
2429
- function addressField(label, value, placeholder, onInput, width) {
2430
- return h('label', { style: { display: 'flex', flexDirection: 'column', gap: 2, width: width || 150 } },
2431
- h('span', { style: tiny }, label),
2432
- h('input', { type: 'text', value: value, placeholder: placeholder, style: field, onInput: onInput }))
2433
- }
2434
- /** Basename of a path-shaped program value, for the row button. */
2435
- function programLabel(value) {
2436
- if (typeof value !== 'string' || value === '') return ''
2437
- var cut = Math.max(value.lastIndexOf('/'), value.lastIndexOf('\\'))
2438
- return cut === -1 ? value : value.slice(cut + 1)
2439
- }
2440
- /**
2441
- * The program picker: ① processes running now (this OS + Windows when
2442
- * reachable), ② a fixed executable picked from disk — the second source is
2443
- * what lets a rule exist before its program is started.
2444
- */
2445
- /** Close the nested picker (it is a dialog of its own). */
2446
- function closePicker() {
2447
- setState(function (prev) { return Object.assign({}, prev, { pickFor: '', pickFilter: '' }) })
2448
- }
2449
-
2450
- // The host half reports which OS it runs on ('windows' | 'wsl' | 'linux' | …);
2451
- // only a posix host has a second (Windows) file system reachable via /mnt.
2452
- var hostIsPosix = !(view !== null && view.side === 'windows')
2453
-
2454
- /**
2455
- * Write a picked path the way the program's own OS spells it.
2456
- *
2457
- * WSL sees the Windows disks under /mnt, so one file browser covers both
2458
- * sides — but a rule has to name `D:\Program Files\...`, not `/mnt/d/...`,
2459
- * or a Windows-side interceptor cannot match the process.
2460
- */
2461
- function pickedPath(value) {
2462
- var match = /^\/mnt\/([A-Za-z])\/(.*)$/.exec(value)
2463
- if (match === null) return value
2464
- return match[1].toUpperCase() + ':\\' + match[2].replace(/\//g, '\\')
2465
- }
2466
-
2467
- /**
2468
- * Entry points: on a posix host the tree starts at `/` and the Windows disks,
2469
- * nothing else. The roots list comes from the host half (which only reloads
2470
- * with dsh web), so this both adds `/` when an older host omits it and drops
2471
- * the workspace/home/temp shortcuts — they only pushed the real start down.
2472
- */
2473
- function withFilesystemRoot(roots, posix) {
2474
- if (posix !== true) return roots
2475
- var kept = roots.filter(function (root) { return root.path === '/' || /^\/mnt\/[A-Za-z](\/|$)/.test(root.path) })
2476
- if (kept.some(function (root) { return root.path === '/' })) return kept
2477
- return [{ name: '根路径 /', path: '/' }].concat(kept)
2478
- }
2479
-
2480
- /**
2481
- * Rows of the file tree, one level at a time.
2482
- *
2483
- * The tree grows IN PLACE: a folder is a row that toggles, not a "enter this
2484
- * directory" navigation, so a path three levels deep costs three clicks and
2485
- * the parent stays visible the whole time.
2486
- */
2487
- function dirRow(dir, depth, chooser) {
2488
- var open = tree.expanded[dir.path] === true
2489
- var node = tree.nodes[dir.path]
2490
- // A folder whose listing came back empty is a LEAF in practice: showing a
2491
- // caret there invites a click that can only disappoint.
2492
- var leaf = node !== undefined && node.dirs.length === 0 && node.files.length === 0
2493
- var rows = [h('div', {
2494
- key: 'd:' + dir.path,
2495
- title: leaf ? dir.path + '(空目录)' : dir.path,
2496
- style: {
2497
- display: 'flex', alignItems: 'center', gap: 4, cursor: leaf ? 'default' : 'pointer',
2498
- padding: '1px 4px', paddingLeft: 4 + depth * 14, borderRadius: 4, fontSize: 12,
2499
- opacity: leaf ? 0.66 : 1,
2500
- },
2501
- 'data-proxy-tree-dir': dir.path,
2502
- 'data-proxy-tree-leaf': leaf ? '1' : '0',
2503
- onClick: leaf ? undefined : function () { toggleDir(dir) },
2504
- onMouseDown: function (event) { event.preventDefault() },
2505
- },
2506
- h('span', { style: { width: 12, opacity: 0.8 } }, leaf ? '·' : open ? '▾' : '▸'),
2507
- h('span', null, (leaf ? '📂 ' : '📁 ') + dir.name),
2508
- tree.loading[dir.path] === true ? h('span', { style: tiny }, '…') : null)]
2509
- if (open === true) rows = rows.concat(treeRows(dir.path, depth + 1, chooser))
2510
- return rows
2511
- }
2512
-
2513
- function treeRows(path, depth, chooser) {
2514
- var node = tree.nodes[path]
2515
- if (node === undefined) {
2516
- return tree.loading[path] === true
2517
- ? [h('div', { key: 'loading:' + path, style: Object.assign({}, tiny, { paddingLeft: 8 + depth * 14 }) }, '读取中…')]
2518
- : []
2519
- }
2520
- var rows = []
2521
- node.dirs.forEach(function (dir) {
2522
- rows = rows.concat(dirRow(dir, depth, chooser))
2523
- })
2524
- node.files.forEach(function (file) {
2525
- rows.push(h('button', {
2526
- key: 'f:' + file.path, type: 'button', title: '选这个程序:' + file.path,
2527
- style: {
2528
- // Same box as a folder row (12px caret slot, then the name), so the
2529
- // indentation lines up — but the slot stays EMPTY: a file cannot be
2530
- // expanded, and an arrow there reads as "click me twice".
2531
- display: 'flex', alignItems: 'center', gap: 4, width: '100%', textAlign: 'left',
2532
- cursor: 'pointer', padding: '1px 4px', paddingLeft: 4 + depth * 14, fontSize: 12,
2533
- background: 'transparent', border: 'none', color: 'inherit', borderRadius: 4,
2534
- },
2535
- 'data-proxy-tree-file': file.path,
2536
- onClick: function () { chooser(file.path) },
2537
- },
2538
- h('span', { style: { width: 12 } }, ''),
2539
- h('span', null, '📄 ' + file.name)))
2540
- })
2541
- return rows
2542
- }
2543
-
2544
- function pickerCard(rule) {
2545
- var needle = state.pickFilter.trim().toLowerCase()
2546
- var items = programs.filter(function (item) { return needle === '' || item.name.toLowerCase().indexOf(needle) !== -1 }).slice(0, 40)
2547
- var chooser = function (value) {
2548
- // Picking a program also picks the mechanism: a SOCKS-aware program is
2549
- // told the upstream address at launch (no mapping), anything else can
2550
- // only reach the tunnel through 127.0.0.1:<same port>.
2551
- var speaksSocks = programSpeaksSocks(value)
2552
- patchRule(rule.id, {
2553
- program: pickedPath(value),
2554
- socksCapable: speaksSocks,
2555
- shadow: speaksSocks ? false : rule.shadow === true || rule.shadowable !== false,
2556
- })
2557
- setState(function (prev) { return Object.assign({}, prev, { pickFor: '', pickFilter: '' }) })
2558
- }
2559
- var tabButton = function (mode, label) {
2560
- var active = pickMode === mode
2561
- return h('button', {
2562
- type: 'button',
2563
- style: Object.assign({}, field, { width: 'auto', cursor: 'pointer', fontWeight: active ? 600 : 400, opacity: active ? 1 : 0.6 }),
2564
- 'data-proxy-pick-mode': mode,
2565
- onClick: function () {
2566
- setPickMode(mode)
2567
- if (mode === 'running') { if (programsLoaded !== true) void loadPrograms() ; return }
2568
- // Switching sides starts a fresh tree for that file system; the read
2569
- // is lazy (only the roots now, folders when expanded).
2570
- var side = mode === 'windows' ? 'windows' : 'local'
2571
- if (tree.side !== side) {
2572
- setTree({ side: side, roots: null, nodes: {}, expanded: {}, loading: {}, error: '' })
2573
- void loadTreeDir('', side)
2574
- } else if (tree.roots === null) void loadTreeDir('', side)
2575
- },
2576
- }, label)
2577
- }
2578
- return h('div', {
2579
- style: { width: 680, maxWidth: '92vw', maxHeight: '80vh', display: 'flex', flexDirection: 'column', padding: 12, borderRadius: 8, background: 'var(--dsw-surface, #fff)', border: '1px solid color-mix(in srgb, currentColor 18%, transparent)' },
2580
- 'data-proxy-picker': rule.id,
2581
- },
2582
- h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 } },
2583
- h('strong', { style: { fontSize: 13 } }, '选择程序'),
2584
- h('span', { style: Object.assign({}, tiny, { flex: 1 }) }, '给规则「' + (rule.label || rule.program || rule.id) + '」选择可执行文件'),
2585
- h('button', {
2586
- type: 'button', style: Object.assign({}, field, { width: 26, cursor: 'pointer' }),
2587
- title: '关闭', 'data-proxy-picker-close': '1',
2588
- onClick: function () { closePicker() },
2589
- }, '×')),
2590
- h('div', { style: { display: 'flex', gap: 6, alignItems: 'center', marginBottom: 6, flexWrap: 'wrap' } },
2591
- tabButton('running', '运行中的程序'),
2592
- // ONE file tab: on WSL the Windows disks are ordinary folders under
2593
- // /mnt, so a second tab would only be a different spelling of the same
2594
- // tree. A pick from there is written back as `D:\…` (see pickedPath).
2595
- tabButton('local', '选择文件'),
2596
- h('span', { style: Object.assign({}, tiny, { marginLeft: 4 }) },
2597
- pickMode === 'running' ? '进程名即程序名,也可直接在上方的输入框手写' : '点文件夹展开,点文件选中;也可以直接用输入框写路径')),
2598
- pickMode === 'running'
2599
- ? h('div', null,
2600
- h('input', {
2601
- type: 'text', value: state.pickFilter, placeholder: '过滤程序名(如 java / navicat)', style: Object.assign({}, field, { marginBottom: 4 }),
2602
- autoFocus: true,
2603
- onInput: function (event) { setState(function (prev) { return Object.assign({}, prev, { pickFilter: event.target.value }) }) },
2604
- }),
2605
- items.length === 0
2606
- ? h('div', { style: tiny }, programsLoaded !== true ? '读取中…' : '没有匹配的程序;直接在上面输入程序名也可以')
2607
- : items.map(function (item) {
2608
- return h('button', {
2609
- key: item.name + ':' + item.side, type: 'button',
2610
- style: { display: 'block', width: '100%', textAlign: 'left', fontSize: 12, padding: '2px 4px', background: 'transparent', border: 'none', color: 'inherit', cursor: 'pointer' },
2611
- title: item.side === 'windows' ? 'Windows 侧进程' : '本侧进程',
2612
- onClick: function () { chooser(item.name) },
2613
- }, item.name + (item.side === 'windows' ? '(Windows)' : ''))
2614
- }))
2615
- : h('div', { style: { flex: 1, minHeight: 220, maxHeight: '58vh', overflowY: 'auto', border: '1px solid color-mix(in srgb, currentColor 12%, transparent)', borderRadius: 6, padding: '4px 2px' }, 'data-proxy-tree': tree.side },
2616
- tree.error !== '' ? h('div', { style: { fontSize: 11, color: '#d9534f', padding: 4 } }, tree.error) : null,
2617
- tree.roots === null
2618
- ? h('div', { style: Object.assign({}, tiny, { padding: 6 }) }, '读取中…')
2619
- // The top level is the list of entry points, each one a folder row:
2620
- // the tree never has a "current directory" to step out of.
2621
- //
2622
- // `/` is added here as well as in the host: the roots list comes from
2623
- // the host half, which only reloads when `dsh web` restarts, and a
2624
- // browser refresh must not leave the tree without the one entry that
2625
- // reaches everything.
2626
- : [].concat.apply([], withFilesystemRoot(tree.roots, hostIsPosix).map(function (root) { return dirRow(root, 0, chooser) }))))
2627
- }
2628
- /**
2629
- * ProxyBridge state of BOTH sides, plus the exact command to run.
2630
- *
2631
- * The web route cannot elevate (a browser click cannot become root/UAC), so
2632
- * "start" writes the profile and hands back the command when rights are
2633
- * missing — the block shows it verbatim instead of a bare failure.
2634
- */
2635
- function redirectorBlock() {
2636
- var dialogState = state
2637
- var info = view === null ? null : view.redirector
2638
- if (info === null || info === undefined) return null
2639
- var describe = function (side, label) {
2640
- var sideState = info[side] || {}
2641
- var text = sideState.available === true
2642
- ? (sideState.version ? 'v' + String(sideState.version) : '已找到')
2643
- : (side === 'windows' && view.side === 'windows' ? '未安装' : '未安装(可选)')
2644
- return h('span', { style: { fontSize: 11, whiteSpace: 'nowrap' }, title: sideState.path || '' },
2645
- label + ':' + text)
2646
- }
2647
- var command = typeof state.redirectorCommand === 'string' ? state.redirectorCommand : ''
2648
- return h('div', {
2649
- style: { marginTop: 8, padding: '6px 8px', border: '1px solid color-mix(in srgb, currentColor 12%, transparent)', borderRadius: 6 },
2650
- 'data-proxy-redirector': '1',
2651
- },
2652
- h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' } },
2653
- h('span', { style: { fontWeight: 600, fontSize: 12 } }, '系统层拦截(ProxyBridge)'),
2654
- describe('local', '本侧'),
2655
- describe('windows', 'Windows'),
2656
- h('span', { style: { fontSize: 11, opacity: 0.75 } },
2657
- info.running === true ? '运行中' : '随代理启停'),
2658
- ),
2659
- h('div', { style: Object.assign({}, tiny, { marginTop: 4, lineHeight: 1.5 }) },
2660
- '覆盖任何方式启动的程序;两端独立进程,启动需 root/管理员(会弹窗提权)。'),
2661
- // No controls of its own: this block reports what the one 启动/停止 pair
2662
- // does, and shows the command only when the automatic start could not
2663
- // elevate (a web click cannot become root).
2664
- command !== ''
2665
- ? h('div', {
2666
- style: Object.assign({}, tiny, { marginTop: 4, fontFamily: 'monospace', wordBreak: 'break-all', userSelect: 'text' }),
2667
- 'data-proxy-redirector-command': '1',
2668
- title: '自动启动提权失败时,在终端里执行(需要 sudo / 管理员)',
2669
- }, command)
2670
- : null)
2671
- }
2672
-
2673
- /**
2674
- * The port suffix of the mapping hint, e.g. `:1521` for "1521,6890".
2675
- *
2676
- * One listener is created per (host,port) pair, so the hint names the first
2677
- * port and says how many there are instead of listing them all.
2678
- */
2679
- function portSuffix(rule) {
2680
- var ports = rule.portsParsed || []
2681
- if (ports.length === 0) return ''
2682
- return ':' + String(ports[0]) + (ports.length > 1 ? ' 等 ' + String(ports.length) + ' 个' : '')
2683
- }
2684
-
2685
- /**
2686
- * The host's verdict for this row, when the row still says what the host saved.
2687
- *
2688
- * Local parsing is a typing PREVIEW: the host owns the real rule (`ruleEffectiveness`
2689
- * + the engine's allow-list). Comparing the texts is how this stays one source of
2690
- * truth — a message like「界面说生效、引擎说不生效」cannot survive the comparison.
2691
- */
2692
- function hostVerdictFor(rule) {
2693
- var view = state.view
2694
- if (view === null || !Array.isArray(view.rules)) return null
2695
- var found = null
2696
- view.rules.forEach(function (row) { if (row !== null && row.id === rule.id) found = row })
2697
- if (found === null) return null
2698
- var same = String(found.program || '').trim() === String(rule.program || '').trim()
2699
- && String(found.hosts || '') === String(rule.hosts || '')
2700
- && String(found.ports || '') === String(rule.ports || '')
2701
- && (found.enabled === true) === (rule.enabled === true)
2702
- return same ? found : null
2703
- }
2704
-
2705
- /** One rule row. */
2706
- function ruleRow(rule) {
2707
- var invalid = (rule.hostsInvalid || []).length > 0 || (rule.portsInvalid || []).length > 0
2708
- // What the ENGINE will conclude, once the host has seen this exact row.
2709
- var hostRow = hostVerdictFor(rule)
2710
- var effective = hostRow === null ? rule.effective : hostRow.effective === true
2711
- var ineffectiveReason = hostRow === null ? rule.ineffectiveReason : hostRow.ineffectiveReason
2712
- // Every row is editable: ProxyBridge hooks the kernel and matches process
2713
- // names, so a rule is machine-wide and the workspace it came from is only
2714
- // a provenance label (shown as 来源).
2715
- return h('div', {
2716
- key: rule.id,
2717
- style: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 6, padding: '5px 0', borderTop: '1px solid color-mix(in srgb, currentColor 10%, transparent)' },
2718
- 'data-proxy-rule': rule.id,
2719
- 'data-proxy-effective': rule.enabled === true && effective === false ? '0' : '1',
2720
- },
2721
- h('label', { style: { display: 'flex', alignItems: 'center', gap: 4, fontSize: 12, width: 58 } },
2722
- h('input', { type: 'checkbox', checked: rule.enabled, onChange: function (event) { patchRule(rule.id, { enabled: event.target.checked }) } }),
2723
- '启用'),
2724
- // The name is typed, not chosen: `java` matches any path (ProxyBridge uses a
2725
- // bare name as *java*), `D:\…\java.exe` matches exactly that executable.
2726
- // The button opens the two-source picker (running process / file tree).
2727
- h('input', {
2728
- type: 'text', value: rule.program, placeholder: '程序名或路径:java / D:\\…\\java.exe',
2729
- style: Object.assign({}, field, { width: 150 }),
2730
- title: '直接输入程序名(如 java,匹配任意路径)或完整路径(精确匹配)',
2731
- 'data-proxy-program': rule.id,
2732
- onInput: function (event) {
2733
- var value = event.target.value
2734
- patchRule(rule.id, { program: value, socksCapable: programSpeaksSocks(value) })
2735
- },
2736
- }),
2737
- h('button', {
2738
- type: 'button',
2739
- style: Object.assign({}, field, { width: 42, cursor: 'pointer' }),
2740
- title: '从运行中的进程或文件树中选择(弹窗)',
2741
- 'data-proxy-pick': rule.id,
2742
- onClick: function () {
2743
- setState(function (prev) { return Object.assign({}, prev, { pickFor: rule.id, pickFilter: '' }) })
2744
- void loadPrograms()
2745
- },
2746
- }, '选…'),
2747
- // Rows a provider generated (yds: "YonCode java", "YonCode git") carry a
2748
- // label so the table says where the rule came from without opening it.
2749
- rule.label === undefined || rule.label === ''
2750
- ? null
2751
- : h('span', {
2752
- style: { fontSize: 10, opacity: 0.8, whiteSpace: 'nowrap' },
2753
- 'data-proxy-label': rule.label,
2754
- title: rule.label + ':' + rule.program,
2755
- }, rule.label),
2756
- h('input', {
2757
- type: 'text', value: rule.hosts, placeholder: 'IP 允许:1.1.1.*, 10.0.0.5(全部写 *;空=本行不生效)',
2758
- style: Object.assign({}, field, { width: 168 }), title: '支持逗号分隔与 * 段通配',
2759
- onInput: function (event) { patchRule(rule.id, parseRuleSpec(Object.assign({}, rule, { hosts: event.target.value }))) },
2760
- }),
2761
- h('input', {
2762
- type: 'text', value: rule.ports, placeholder: '端口:1521, 1000-1010(全部写 *;空=本行不生效)',
2763
- style: Object.assign({}, field, { width: 104 }), title: '支持逗号分隔与范围',
2764
- onInput: function (event) { patchRule(rule.id, parseRuleSpec(Object.assign({}, rule, { ports: event.target.value }))) },
2765
- }),
2766
- // No mapping switch: whether a program can take a SOCKS address decides
2767
- // it (SOCKS-aware → nothing to map; everything else → mapped on the same
2768
- // port), so the row only reports HOW the traffic leaves. "直连" used to be
2769
- // shown here and read like "no proxy at all" — it always means SOCKS.
2770
- h('span', {
2771
- style: { fontSize: 10, opacity: 0.75, whiteSpace: 'nowrap' },
2772
- 'data-proxy-map': rule.shadow === true ? 'mapped' : 'socks',
2773
- title: rule.shadow === true
2774
- ? '这个程序不能配 SOCKS(如 Navicat / JDBC),自动映射 127.0.0.1:同端口走代理'
2775
- : (rule.socksCapable === true
2776
- ? '这个程序能直接吃 SOCKS 地址(ProxyBridge 按进程拦截,或启动时注入),无需映射'
2777
- : '通过 SOCKS 代理(ProxyBridge 按进程拦截,或启动时注入),无需映射'),
2778
- }, rule.shadow === true ? '127.0.0.1' + portSuffix(rule) : 'SOCKS'),
2779
- rule.source === 'yds'
2780
- ? h('span', { style: { fontSize: 10, opacity: 0.55 }, title: 'yds start 自动生成的规则:删除后会在下次启动时重新写入' }, 'yds 自动')
2781
- : null,
2782
- rule.origin !== undefined && rule.origin !== ''
2783
- ? h('span', {
2784
- style: { fontSize: 10, opacity: 0.55, whiteSpace: 'nowrap' },
2785
- title: '这一行由哪个工作区写入(仅供参考,规则本身是整机生效的):' + rule.workspace,
2786
- }, '来源 ' + rule.origin)
2787
- : null,
2788
- h('button', {
2789
- type: 'button', style: { ...field, width: 26, cursor: 'pointer' }, title: '删除这一行',
2790
- onClick: function () { dropRule(rule.id) },
2791
- }, '×'),
2792
- // A row can look "on" and still apply to nothing: enabled is only one of
2793
- // four required inputs (program / IP / port, with `*` for "everything").
2794
- rule.enabled === true && effective === false
2795
- ? h('div', { style: { flexBasis: '100%', fontSize: 11, color: '#d9534f' }, 'data-proxy-ineffective': rule.id },
2796
- '不生效:' + (ineffectiveReason || '缺少程序 / IP / 端口'))
2797
- : null,
2798
- invalid
2799
- ? h('div', { style: { flexBasis: '100%', fontSize: 11, color: '#d9534f' } },
2800
- (rule.hostsInvalid || []).length > 0 ? '无效 IP:' + rule.hostsInvalid.join(', ') + ' ' : '',
2801
- (rule.portsInvalid || []).length > 0 ? '无效端口:' + rule.portsInvalid.join(', ') : '')
2802
- : null)
2803
- }
2804
-
2805
- /**
2806
- * One footer button shape for every action.
2807
- *
2808
- * `S.buttonOff` is the DISABLED style (opacity .4), so painting an enabled
2809
- * action with it made 启动/停止 look equally dead — you could not tell which
2810
- * one the dialog wanted you to press. Here the box is identical for all
2811
- * three and only the actionable one is filled.
2812
- * @param {{label: string, primary?: boolean, disabled?: boolean, onClick: Function, action: string, title?: string}} spec - button.
2813
- * @returns {object} the button element.
2814
- */
2815
- function dialogButton(spec) {
2816
- var filled = spec.primary === true && spec.disabled !== true
2817
- return h('button', {
2818
- type: 'button',
2819
- disabled: spec.disabled === true,
2820
- 'data-proxy-action': spec.action,
2821
- title: spec.title || '',
2822
- style: {
2823
- font: 'inherit', fontFamily: 'inherit', fontSize: 'inherit', lineHeight: 1.4,
2824
- minWidth: 84, height: 28, padding: '0 14px', borderRadius: 4, boxSizing: 'border-box',
2825
- cursor: spec.disabled === true ? 'default' : 'pointer',
2826
- opacity: spec.disabled === true ? 0.45 : 1,
2827
- color: filled ? '#fff' : 'inherit',
2828
- background: filled ? 'var(--dsw-accent, #2f6feb)' : 'transparent',
2829
- border: '1px solid ' + (filled ? 'var(--dsw-accent, #2f6feb)' : 'color-mix(in srgb, currentColor 34%, transparent)'),
2830
- },
2831
- onClick: spec.onClick,
2832
- }, spec.label)
2833
- }
2834
-
2835
- var running = view !== null && view.running === true
2836
- var statusLine = view === null
2837
- ? (state.loading ? '读取中…' : '')
2838
- : (running ? '运行中' : '未运行')
2839
- + (view.shared === true ? ' · 全机共享' : '')
2840
- return h('div', {
2841
- style: { position: 'fixed', inset: 0, zIndex: 1000, background: 'color-mix(in srgb, #000 38%, transparent)', display: 'flex', alignItems: 'center', justifyContent: 'center' },
2842
- 'data-proxy-dialog': '1',
2843
- onMouseDown: onClose,
2844
- },
2845
- // Every control (including the program picker's filter box and the row
2846
- // buttons) must agree with the card's font; form controls ignore
2847
- // inheritance unless told otherwise.
2848
- h('style', { key: 'proxy-dialog-font' },
2849
- '[data-proxy-dialog] input, [data-proxy-dialog] button, [data-proxy-dialog] select, [data-proxy-dialog] textarea { font-family: inherit; font-size: inherit; }'),
2850
- h('div', {
2851
- style: Object.assign({}, S.card || {}, {
2852
- width: 760, maxWidth: '94vw', padding: 14, borderRadius: 8, display: 'flex', flexDirection: 'column', gap: 2,
2853
- background: 'var(--dsw-surface, #ffffff)', color: 'inherit', boxShadow: '0 18px 40px rgba(0,0,0,.35)', maxHeight: '88vh', overflowY: 'auto',
2854
- // One dialog in two shells: the sidebar inherits the DSH shell's font,
2855
- // the standalone window the IDE chrome's. Pin the chrome stack so both
2856
- // shapes measure identically (`--dsw-font-mono` is IDE-page-only).
2857
- fontFamily: CHROME_FAMILY, fontSize: DEFAULT_FONT_SIZE + 'px',
2858
- }),
2859
- onMouseDown: function (event) { event.stopPropagation() },
2860
- },
2861
- h('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
2862
- h('span', { style: { fontWeight: 600 } }, '代理'),
2863
- h('span', { style: S.spacer }),
2864
- h('button', {
2865
- type: 'button', 'data-proxy-close': '1', title: '关闭', onClick: function () { closeDialog() },
2866
- style: { font: 'inherit', fontFamily: 'inherit', fontSize: 'inherit', width: 24, height: 24, lineHeight: 1, padding: 0, cursor: 'pointer', color: 'inherit', background: 'transparent', border: '1px solid transparent', borderRadius: 4 },
2867
- }, '×')),
2868
- h('div', {
2869
- style: Object.assign({}, tiny, { marginTop: 2, lineHeight: 1.5 }),
2870
- title: view !== null && typeof view.configPath === 'string'
2871
- ? '全机一份配置与一个引擎:' + view.configPath + '(规则按工作区打标签,端口只绑一次)'
2872
- : '',
2873
- }, statusLine),
2874
- // A previous dsh left this engine behind (the Ctrl+C leak before the
2875
- // lifecycle fix). The host adopted it on mount, so it keeps working —
2876
- // say so, and offer the stop instead of leaving the user to wonder who
2877
- // started it.
2878
- view !== null && view.inherited === true
2879
- ? h('div', {
2880
- 'data-proxy-inherited': '1',
2881
- style: {
2882
- marginTop: 6, padding: '6px 8px', borderRadius: 4, fontSize: 11, lineHeight: 1.5,
2883
- display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap',
2884
- border: '1px solid color-mix(in srgb, #c98a1b 45%, transparent)',
2885
- background: 'color-mix(in srgb, #c98a1b 10%, transparent)',
2886
- },
2887
- },
2888
- h('span', null,
2889
- '代理由上一个会话启动(引擎 pid ' + (view.inheritedPid || view.pid || '?')
2890
- + (view.inheritedFrom > 0 ? ',原 dsh pid ' + view.inheritedFrom : '')
2891
- + '),本会话已接管:可直接使用,或在这里停止。'),
2892
- h('span', { style: S.spacer }),
2893
- dialogButton({
2894
- action: 'stop-inherited',
2895
- label: state.busy === 'stop' ? '停止中…' : '停止代理',
2896
- disabled: state.busy !== '',
2897
- onClick: function () { act('stop') },
2898
- title: '停止上一个会话留下的代理引擎,并清除系统层拦截与 git 代理',
2899
- }))
2900
- : null,
2901
- draft === null
2902
- ? h('div', { style: { marginTop: 10, fontSize: 12, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
2903
- state.loading ? '读取中…' : null,
2904
- state.loading ? null : h('span', { style: { color: '#d9534f' } }, state.error || '没有配置'),
2905
- state.loading ? null : h('button', {
2906
- type: 'button', style: Object.assign({}, field, { width: 'auto', cursor: 'pointer' }),
2907
- onClick: function () { load() },
2908
- }, '重试'))
2909
- : h('div', null,
2910
- // 上部:代理地址
2911
- h('div', { style: { display: 'flex', alignItems: 'flex-end', gap: 8, marginTop: 10, flexWrap: 'wrap' } },
2912
- addressField('代理地址(SOCKS5 主机)', draft.socks.host, '如 10.3.91.121',
2913
- function (event) { setState(function (prev) { return Object.assign({}, prev, { draft: Object.assign({}, prev.draft, { socks: Object.assign({}, prev.draft.socks, { host: event.target.value }) }) }) }) }),
2914
- addressField('端口', draft.socks.port, '1080',
2915
- function (event) { setState(function (prev) { return Object.assign({}, prev, { draft: Object.assign({}, prev.draft, { socks: Object.assign({}, prev.draft.socks, { port: event.target.value }) }) }) }) }, 90),
2916
- addressField('本地监听端口', draft.listenPort, '11081',
2917
- function (event) { setState(function (prev) { return Object.assign({}, prev, { draft: Object.assign({}, prev.draft, { listenPort: event.target.value }) }) }) }, 110)),
2918
- h('div', { style: Object.assign({}, tiny, { marginTop: 6, lineHeight: 1.5 }) },
2919
- '规则整机生效(不区分工作区)。主路 ProxyBridge 按进程名在系统层拦截;'
2920
- + '未运行时退回注入与 127.0.0.1 映射。'),
2921
- // 系统层拦截器(ProxyBridge):主路,两端各自独立
2922
- redirectorBlock(),
2923
- // 下部:规则列表
2924
- state.error !== '' && draft !== null
2925
- ? h('div', { style: { marginTop: 8, fontSize: 11, color: '#d9534f' } }, state.error)
2926
- : null,
2927
- h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginTop: 12 } },
2928
- h('span', { style: { fontWeight: 600, fontSize: 12 } }, '代理规则'),
2929
- h('span', { style: tiny }, '程序 / IP / 端口'),
2930
- h('span', { style: S.spacer }),
2931
- h('button', {
2932
- type: 'button', 'data-proxy-add': '1', onClick: addRule,
2933
- style: { font: 'inherit', fontFamily: 'inherit', fontSize: 'inherit', height: 26, padding: '0 10px', cursor: 'pointer', color: 'inherit', background: 'transparent', border: '1px solid color-mix(in srgb, currentColor 34%, transparent)', borderRadius: 4 },
2934
- }, '+ 添加规则')),
2935
- draft.rules.length === 0
2936
- ? h('div', { style: Object.assign({}, tiny, { marginTop: 6 }) }, '没有规则:没有程序走代理')
2937
- : h('div', { style: { marginTop: 4 } }, draft.rules.map(ruleRow)),
2938
- (state.note === '' ? null : h('div', { style: { fontSize: 11, opacity: 0.7, marginTop: 8 } }, state.note)),
2939
- h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, flexWrap: 'wrap' } },
2940
- h('span', { style: Object.assign({}, tiny, { minWidth: 64 }), 'data-proxy-autosave': state.saving === true ? 'saving' : 'saved' },
2941
- state.saving === true ? '保存中…' : '自动保存'),
2942
- dialogButton({
2943
- action: 'start', label: state.busy === 'start' ? '启动中…' : '启动',
2944
- // Exactly one of start/stop is the next thing to do, so exactly one
2945
- // of them is filled: grey is reserved for "nothing to do here".
2946
- primary: !running,
2947
- disabled: state.busy !== '' || running,
2948
- onClick: function () { act('start') },
2949
- title: '启动代理引擎 + 系统层拦截(需要时弹提权)+ 写入 git 代理',
2950
- }),
2951
- dialogButton({
2952
- action: 'stop', label: state.busy === 'stop' ? '停止中…' : '停止',
2953
- primary: running,
2954
- disabled: state.busy !== '' || !running,
2955
- onClick: function () { act('stop') },
2956
- title: '停止引擎、系统层拦截,并清除 git 代理',
2957
- }),
2958
- // No separate git buttons: the git entry is written on 启动 and cleared
2959
- // on 停止 (and on host exit) together with the engine and the
2960
- // redirector, so one control governs the whole tunnel.
2961
- h('span', { style: Object.assign({}, tiny, { marginLeft: 'auto' }) },
2962
- '启动同时写入 git 代理,停止同时清除')))),
2963
- // The program picker is its own dialog on top of this one: a tree with two
2964
- // lazily-loaded roots does not fit inside a rule row.
2965
- state.pickFor === ''
2966
- ? null
2967
- : h('div', {
2968
- style: { position: 'fixed', inset: 0, zIndex: 1001, background: 'color-mix(in srgb, #000 45%, transparent)', display: 'flex', alignItems: 'center', justifyContent: 'center' },
2969
- 'data-proxy-picker-dialog': '1',
2970
- onMouseDown: function (event) { event.stopPropagation(); closePicker() },
2971
- },
2972
- h('div', { onMouseDown: function (event) { event.stopPropagation() } },
2973
- pickerCard((state.draft === null ? { id: '', program: '' } : state.draft.rules.filter(function (rule) { return rule.id === state.pickFor })[0]) || { id: state.pickFor, program: '' })))
2974
- )
2975
- }
2976
-
2977
2034
  /** Scaled CSS for viewers that paint their own font (CodeMirror pins 13px). */
2978
2035
  function viewerFontCss(size) {
2979
2036
  return '[data-workbench="ris-ide"] .cm-editor{font-size:' + size + 'px !important}'
@@ -4306,32 +3363,68 @@ window.__ModuleLoader__.load({
4306
3363
  ]
4307
3364
  }
4308
3365
 
4309
- /** Copy text through the async clipboard API, with a legacy fallback. */
3366
+ /**
3367
+ * Copy text through the async clipboard API, with a legacy fallback.
3368
+ *
3369
+ * `writeText` can REJECT even in a click handler: when the workbench page is
3370
+ * embedded in the risd maintenance iframe, the parent's permissions policy may
3371
+ * block clipboard-write, and an unhandled rejection here used to surface as
3372
+ * 「后台任务出错」 with the copy silently lost (m09396 ③). So every failure —
3373
+ * missing API, rejected promise, denied permission — falls back to the
3374
+ * textarea + execCommand trick, which only needs the click's user activation.
3375
+ * @param {string} text - the text to copy.
3376
+ * @returns {Promise<boolean>} true when the clipboard (or the fallback) took it.
3377
+ */
4310
3378
  function copyText(text) {
4311
3379
  var value = String(text === undefined || text === null ? '' : text)
3380
+ function legacy() {
3381
+ var previousFocus = null
3382
+ var previousRange = null
3383
+ try {
3384
+ previousFocus = document.activeElement
3385
+ var selection = typeof window.getSelection === 'function' ? window.getSelection() : null
3386
+ if (selection !== null && selection.rangeCount > 0) previousRange = selection.getRangeAt(0).cloneRange()
3387
+ } catch { /* no selection API: nothing to restore */ }
3388
+ try {
3389
+ var area = document.createElement('textarea')
3390
+ area.value = value
3391
+ area.setAttribute('readonly', '1')
3392
+ area.style.position = 'fixed'
3393
+ area.style.opacity = '0'
3394
+ document.body.appendChild(area)
3395
+ area.select()
3396
+ var ok = document.execCommand('copy')
3397
+ document.body.removeChild(area)
3398
+ return ok === true
3399
+ } catch {
3400
+ return false
3401
+ } finally {
3402
+ // The textarea stole focus (and the selection): put the user back where
3403
+ // they were, or the next keystroke lands on the body (review C3-P2-13).
3404
+ try {
3405
+ if (previousFocus !== null && typeof previousFocus.focus === 'function') {
3406
+ previousFocus.focus({ preventScroll: true })
3407
+ }
3408
+ if (previousRange !== null) {
3409
+ var restored = window.getSelection()
3410
+ restored.removeAllRanges()
3411
+ restored.addRange(previousRange)
3412
+ }
3413
+ } catch { /* best effort */ }
3414
+ }
3415
+ }
4312
3416
  try {
4313
3417
  if (typeof navigator !== 'undefined' && navigator !== null
4314
3418
  && navigator.clipboard !== undefined && typeof navigator.clipboard.writeText === 'function') {
4315
- void navigator.clipboard.writeText(value)
4316
- return true
3419
+ return Promise.resolve(navigator.clipboard.writeText(value)).then(
3420
+ function () { return true },
3421
+ function () { return legacy() },
3422
+ )
4317
3423
  }
4318
3424
  } catch {
4319
3425
  // fall through to the textarea trick
4320
3426
  }
4321
- try {
4322
- var area = document.createElement('textarea')
4323
- area.value = value
4324
- area.setAttribute('readonly', '1')
4325
- area.style.position = 'fixed'
4326
- area.style.opacity = '0'
4327
- document.body.appendChild(area)
4328
- area.select()
4329
- var ok = document.execCommand('copy')
4330
- document.body.removeChild(area)
4331
- return ok === true
4332
- } catch {
4333
- return false
4334
- }
3427
+ return Promise.resolve(legacy())
4335
3428
  }
4336
3429
 
4337
3430
  /** Basename of a slash path ('' when empty). */
@@ -7111,7 +6204,9 @@ window.__ModuleLoader__.load({
7111
6204
  onClick: function () {
7112
6205
  var entry = treeMenu.entry
7113
6206
  setTreeMenu(null)
7114
- notify(copyText(fileBaseName(entry.path)) ? '已复制文件名:' + fileBaseName(entry.path) : '复制失败:剪贴板不可用')
6207
+ void copyText(fileBaseName(entry.path)).then(function (ok) {
6208
+ notify(ok ? '已复制文件名:' + fileBaseName(entry.path) : '复制失败:剪贴板不可用')
6209
+ })
7115
6210
  },
7116
6211
  }, '复制文件名'),
7117
6212
  h('button', {
@@ -7119,7 +6214,9 @@ window.__ModuleLoader__.load({
7119
6214
  onClick: function () {
7120
6215
  var entry = treeMenu.entry
7121
6216
  setTreeMenu(null)
7122
- notify(copyText(entry.path) ? '已复制路径:' + entry.path : '复制失败:剪贴板不可用')
6217
+ void copyText(entry.path).then(function (ok) {
6218
+ notify(ok ? '已复制路径:' + entry.path : '复制失败:剪贴板不可用')
6219
+ })
7123
6220
  },
7124
6221
  }, '复制文件路径'),
7125
6222
  h('button', {
@@ -7575,34 +6672,65 @@ window.__ModuleLoader__.load({
7575
6672
  })))
7576
6673
  }
7577
6674
 
6675
+ /**
6676
+ * One stored IDE-tab blob, or null when it is absent/junk. Parsing is per key:
6677
+ * `dsh-ris-ide:ui:*` also holds non-JSON preferences (`…:compact-max` = 'log'),
6678
+ * and one of those used to abort the whole legacy scan (C review P2).
6679
+ * @param {string|null} raw - the localStorage value.
6680
+ * @returns {object|null} the parsed blob.
6681
+ */
6682
+ function parseSavedBlob(raw) {
6683
+ if (raw === null || raw === undefined) return null
6684
+ try {
6685
+ var blob = JSON.parse(raw)
6686
+ return blob !== null && typeof blob === 'object' ? blob : null
6687
+ } catch (error) {
6688
+ return null
6689
+ }
6690
+ }
6691
+
7578
6692
  /**
7579
6693
  * The saved layout of one IDE tab: `{ui:{maximized,section}, sizes, font,
7580
- * theme, files, file}`. Persisted per tab under `dsh-ris-ide:ui:<key>`.
6694
+ * theme, files, file}`. Persisted per tab + WORKSPACE under
6695
+ * `dsh-ris-ide:ui:<key>@<cwd>` (m13444).
7581
6696
  *
7582
- * The workspace tab used to be keyed per PROGRAM (the panel passed the first
7583
- * program's meta), so a user's maximised pane / colour scheme / font size could
7584
- * silently reset after that key became `…:workspace`. When the exact key has
7585
- * nothing saved, adopt the first other `dsh-ris-ide:ui:*` entry and let the
7586
- * normal persist effect copy it to the current key.
6697
+ * Pre-m13444 keys had no workspace suffix. Migration is one-shot: the tab's
6698
+ * own legacy key (`…:<key>` without `@…`) is adopted ONCE and deleted, so the
6699
+ * next workspace does not inherit the same open tabs again (C review P1-2).
6700
+ * Same-workspace tabs may still adopt each other (the old per-program key
6701
+ * behaviour); another workspace's blob is never adopted.
7587
6702
  * @param {string} storageKey - the current tab's key.
6703
+ * @param {string} [workspaceKey] - the workspace this tab belongs to.
7588
6704
  * @returns {object|null} the saved blob.
7589
6705
  */
7590
- function readSavedUi(storageKey) {
6706
+ function readSavedUi(storageKey, workspaceKey) {
7591
6707
  try {
7592
6708
  if (typeof localStorage === 'undefined') return null
7593
- var raw = localStorage.getItem(storageKey)
7594
- if (raw !== null) {
7595
- var own = JSON.parse(raw)
7596
- return own !== null && typeof own === 'object' ? own : null
7597
- }
6709
+ var own = parseSavedBlob(localStorage.getItem(storageKey))
6710
+ if (own !== null) return own
7598
6711
  if (typeof localStorage.key !== 'function') return null
6712
+ var scoped = typeof workspaceKey === 'string' && workspaceKey !== ''
6713
+ if (scoped === true) {
6714
+ var at = storageKey.lastIndexOf('@')
6715
+ var legacyKey = at > 0 ? storageKey.slice(0, at) : null
6716
+ if (legacyKey !== null) {
6717
+ var migrated = parseSavedBlob(localStorage.getItem(legacyKey))
6718
+ if (migrated !== null) {
6719
+ try { localStorage.removeItem(legacyKey) } catch (removeError) { /* private mode */ }
6720
+ return migrated
6721
+ }
6722
+ }
6723
+ }
7599
6724
  for (var index = 0; index < localStorage.length; index += 1) {
7600
6725
  var key = localStorage.key(index)
7601
6726
  if (typeof key !== 'string' || key.indexOf('dsh-ris-ide:ui:') !== 0 || key === storageKey) continue
7602
- var legacyRaw = localStorage.getItem(key)
7603
- if (legacyRaw === null) continue
7604
- var legacy = JSON.parse(legacyRaw)
7605
- if (legacy !== null && typeof legacy === 'object') return legacy
6727
+ // Only a tab of THIS workspace: split at the LAST `@`, so a cwd that
6728
+ // itself contains an `@` cannot match another workspace (C review P2).
6729
+ if (scoped !== true) continue
6730
+ var splitAt = key.lastIndexOf('@')
6731
+ if (splitAt <= 0 || key.slice(splitAt + 1) !== workspaceKey) continue
6732
+ var blob = parseSavedBlob(localStorage.getItem(key))
6733
+ if (blob !== null) return blob
7606
6734
  }
7607
6735
  return null
7608
6736
  } catch (error) {
@@ -7773,6 +6901,21 @@ window.__ModuleLoader__.load({
7773
6901
  + '@supports not selector(::-webkit-scrollbar){'
7774
6902
  + '[data-workbench="ris-ide"] *{scrollbar-width:thin;scrollbar-color:rgba(140,140,140,0.55) rgba(127,127,127,0.10)}}'
7775
6903
 
6904
+ /**
6905
+ * File-tree hover affordance: a faint grey row background under the pointer.
6906
+ *
6907
+ * A background changes no metrics, so the row and every sibling stay put —
6908
+ * padding/height hacks would make the tree jump under the mouse. The selected
6909
+ * rows (S.treeRowOn / treeRowMulti) carry their tint as an INLINE style, so
6910
+ * this stylesheet-level hover always loses to them: 「优先级低于选中后的背景色」
6911
+ * holds without extra rules (user口径: hover 用浅灰背景,别比选中色重). Underline
6912
+ * was tried first and was too subtle at a 14px row height.
6913
+ */
6914
+ var TREE_HOVER_CSS = '[data-workbench="ris-ide"] [data-tree-path]:hover'
6915
+ // The plain rgba line is the fallback for engines without `color-mix`
6916
+ // (Chromium < 111): without it the hover rule would be dropped entirely.
6917
+ + '{background:rgba(0,0,0,0.05);background:color-mix(in srgb, currentColor 7%, transparent)}'
6918
+
7776
6919
  /**
7777
6920
  * The editor's find panel, restyled to belong to the IDE (user口径: 美化一下
7778
6921
  * 编辑器的搜索面板,风格和整体不一致). CodeMirror ships a 2018-looking strip:
@@ -8277,13 +7420,18 @@ window.__ModuleLoader__.load({
8277
7420
  })
8278
7421
  }
8279
7422
  function ProgramWorkbench(props) {
8280
- /** The 「代理」 dialog (address + rule table); see `ProxyDialog`. */
8281
- var [proxyOpen, setProxyOpen] = useState(false)
8282
7423
  var scope = props ? props.scope : undefined
8283
7424
  var tab = props ? props.tab : undefined
8284
7425
  var meta = tab !== null && tab !== undefined && tab.meta !== null && typeof tab.meta === 'object' ? tab.meta : {}
8285
7426
  var sessionId = scope ? scope.sessionId : undefined
8286
7427
  var cwd = scope ? scope.cwd : undefined
7428
+ /**
7429
+ * Everything that remembers a WORKSPACE (open file tabs, recent history,
7430
+ * layout, search results) is scoped by this key: two workspaces are two
7431
+ * different file trees, so a tab or a `git grep` hit from one must never
7432
+ * appear in the other (m13444).
7433
+ */
7434
+ var workspaceKey = typeof cwd === 'string' && cwd !== '' ? cwd : 'default'
8287
7435
  var programs = Array.isArray(props.programs) ? props.programs : []
8288
7436
  var metaKind = typeof meta.kind === 'string' ? meta.kind : 'spring'
8289
7437
  var metaLogPath = typeof meta.logPath === 'string' ? meta.logPath : ''
@@ -8311,8 +7459,12 @@ window.__ModuleLoader__.load({
8311
7459
  * across suspends, so reading `dbg` from its closure would be stale. */
8312
7460
  var dbgRef = useRef(dbg)
8313
7461
  dbgRef.current = dbg
8314
- var storageKey = 'dsh-ris-ide:ui:' + (programKey !== '' ? programKey : (metaLogPath !== '' ? metaLogPath : 'workspace'))
8315
- var savedUi = readSavedUi(storageKey)
7462
+ var storageKey = 'dsh-ris-ide:ui:' + (programKey !== '' ? programKey : (metaLogPath !== '' ? metaLogPath : 'workspace')) + '@' + workspaceKey
7463
+ // Read the saved blob ONCE per mount (it only seeds useState initializers
7464
+ // below). The read also runs the one-shot legacy migration — readSavedUi
7465
+ // removes the key it adopted — so calling it per render would re-probe
7466
+ // localStorage on every keystroke (评审 20261109-2326 客户端 P2).
7467
+ var [savedUi] = useState(function () { return readSavedUi(storageKey, workspaceKey) })
8316
7468
 
8317
7469
  var [consoleBusy, setConsoleBusy] = useState('')
8318
7470
  /** Which action that row mask is running (`start|stop|restart|debug`). */
@@ -8380,6 +7532,19 @@ var [ui, setUi] = useState(function () {
8380
7532
  * query (or the `git grep` output) away, so the same row can be reopened.
8381
7533
  */
8382
7534
  var searchCacheRef = useRef(new Map())
7535
+ /**
7536
+ * Search cache key: `kind:workspace\0query`. The workspace MUST be part of
7537
+ * it — `git grep` runs against one tree, so replaying another tree's hits
7538
+ * (or dropping the new tree's entry when invalidating) would cross
7539
+ * workspaces (m13444).
7540
+ */
7541
+ function searchKey(kind, text) {
7542
+ return kind + ':' + workspaceKey + '\u0000' + text
7543
+ }
7544
+ /** A workspace switch replaces the tree under every cached payload. */
7545
+ useEffect(function () {
7546
+ searchCacheRef.current.clear()
7547
+ }, [workspaceKey])
8383
7548
  /**
8384
7549
  * Bumped when the cached results for the CURRENT query must be thrown away
8385
7550
  * (Ctrl+R, or a save in this window). `searchCacheRef` is keyed by query text
@@ -9431,6 +8596,46 @@ var [ui, setUi] = useState(function () {
9431
8596
  }
9432
8597
  return true
9433
8598
  }
8599
+ /**
8600
+ * Answer the maintenance page's questions about unsaved buffers, and save
8601
+ * them all on request (m10900).
8602
+ *
8603
+ * The page embeds this window in an iframe on a different origin (daemon
8604
+ * port vs the dsh web port), so it cannot read `docs`; it asks over
8605
+ * postMessage before it reloads itself. Only the immediate parent is served,
8606
+ * and only these two message shapes, so another opener cannot drive the
8607
+ * editor. A page that predates the bridge simply never asks.
8608
+ */
8609
+ useEffect(function () {
8610
+ var reply = function (payload) {
8611
+ try { window.parent.postMessage(payload, '*') } catch { /* parent gone */ }
8612
+ }
8613
+ var onMessage = function (event) {
8614
+ if (event.source !== window.parent) return
8615
+ var data = event.data
8616
+ if (data === null || typeof data !== 'object') return
8617
+ if (data.type === 'dsh-ris-ide:probe-dirty') {
8618
+ var dirty = openFiles.filter(function (path) { return isDirty(path) === true })
8619
+ reply({
8620
+ type: 'dsh-ris-ide:dirty-report',
8621
+ requestId: data.requestId,
8622
+ count: dirty.length,
8623
+ names: dirty.slice(0, 5).map(fileBaseName),
8624
+ })
8625
+ return
8626
+ }
8627
+ if (data.type === 'dsh-ris-ide:save-all') {
8628
+ var pending = openFiles.filter(function (path) { return isDirty(path) === true })
8629
+ Promise.resolve(saveBulk(pending)).then(function (ok) {
8630
+ reply({ type: 'dsh-ris-ide:save-all-done', requestId: data.requestId, ok: ok === true })
8631
+ }, function () {
8632
+ reply({ type: 'dsh-ris-ide:save-all-done', requestId: data.requestId, ok: false })
8633
+ })
8634
+ }
8635
+ }
8636
+ window.addEventListener('message', onMessage)
8637
+ return function () { window.removeEventListener('message', onMessage) }
8638
+ }, [openFiles, docs, viewerStates])
9434
8639
  /**
9435
8640
  * Bulk close (right-click → 关闭其他/全部关闭). Dirty tabs are never dropped
9436
8641
  * silently: one prompt offers save-all / discard-all / cancel for the batch.
@@ -10171,8 +9376,8 @@ var [ui, setUi] = useState(function () {
10171
9376
  var query = String(raw === undefined || raw === null ? '' : raw).trim()
10172
9377
  var dropped = false
10173
9378
  if (query !== '') {
10174
- dropped = searchCacheRef.current.delete('content:' + query) || dropped
10175
- dropped = searchCacheRef.current.delete('name:' + query) || dropped
9379
+ dropped = searchCacheRef.current.delete(searchKey('content', query)) || dropped
9380
+ dropped = searchCacheRef.current.delete(searchKey('name', query)) || dropped
10176
9381
  }
10177
9382
  // Nothing cached: whatever is on screen came from a run that is still
10178
9383
  // fresh (or is already in flight), so a second kick would only abort it.
@@ -10183,7 +9388,7 @@ var [ui, setUi] = useState(function () {
10183
9388
  useEffect(function () {
10184
9389
  var text = treeQuery.trim()
10185
9390
  if (text === '') { setSearchHits(null); setSearchBusy(false); return undefined }
10186
- var cached = searchCacheRef.current.get('name:' + text)
9391
+ var cached = searchCacheRef.current.get(searchKey('name', text))
10187
9392
  if (cached !== undefined && cached !== null) {
10188
9393
  setSearchHits(cached)
10189
9394
  setSearchBusy(false)
@@ -10206,7 +9411,7 @@ var [ui, setUi] = useState(function () {
10206
9411
  }, controller === null ? undefined : controller.signal).then(function () {
10207
9412
  if (cancelled) return
10208
9413
  var payload = searchHitPayload({ matches: matches.slice(), dirs: {} }, cwd)
10209
- rememberSearchEntry(searchCacheRef.current, 'name:' + text, payload)
9414
+ rememberSearchEntry(searchCacheRef.current, searchKey('name', text), payload)
10210
9415
  setSearchHits(payload)
10211
9416
  setSearchBusy(false)
10212
9417
  }).catch(function (problem) {
@@ -10231,7 +9436,7 @@ var [ui, setUi] = useState(function () {
10231
9436
  useEffect(function () {
10232
9437
  var text = treeQuery.trim()
10233
9438
  if (text.length < 2) { setContentHits([]); setContentBusy(false); return undefined }
10234
- var cached = searchCacheRef.current.get('content:' + text)
9439
+ var cached = searchCacheRef.current.get(searchKey('content', text))
10235
9440
  if (cached !== undefined && Array.isArray(cached)) {
10236
9441
  setContentHits(cached)
10237
9442
  setContentBusy(false)
@@ -10251,7 +9456,7 @@ var [ui, setUi] = useState(function () {
10251
9456
  }, controller === null ? undefined : controller.signal).then(function () {
10252
9457
  if (cancelled) return
10253
9458
  var payload = hits.slice()
10254
- rememberSearchEntry(searchCacheRef.current, 'content:' + text, payload)
9459
+ rememberSearchEntry(searchCacheRef.current, searchKey('content', text), payload)
10255
9460
  setContentHits(payload)
10256
9461
  setContentBusy(false)
10257
9462
  }).catch(function (problem) {
@@ -10349,24 +9554,9 @@ var [ui, setUi] = useState(function () {
10349
9554
  applyFind(0)
10350
9555
  }
10351
9556
  }
10352
- var runningSignature = programs.filter(function (program) {
10353
- return program.running !== null && program.running !== undefined && program.running.alive === true
10354
- }).map(function (program) { return program.kind + '|' + program.logPath }).join(',')
10355
- // First load with no explicit target: pick the first RUNNING service (else the
10356
- // first program) so both panes show something instead of a blank placeholder.
10357
- useEffect(function () {
10358
- var running = programs.filter(function (program) {
10359
- return program.running !== null && program.running !== undefined && program.running.alive === true
10360
- })
10361
- if (running.length === 0) return
10362
- if (activePathRef.current !== '') return
10363
- var preferred = running.filter(function (program) { return program.kind === 'spring' })[0] || running[0]
10364
- if (preferred !== undefined) {
10365
- setActivePath(preferred.logPath)
10366
- activePathRef.current = preferred.logPath
10367
- }
10368
- }, [runningSignature, sessionId])
10369
-
9557
+ // No auto-pick on first load (m07431): the console starts with no selected row,
9558
+ // so the log pane must stay parked on its placeholder instead of loading and
9559
+ // locating a file the user never asked for. A click on a row is the only way in.
10370
9560
  /** Finish a "save then close": the viewer's saveState is the signal. */
10371
9561
  useEffect(function () {
10372
9562
  if (pendingSaveClose === undefined) return
@@ -10592,6 +9782,7 @@ var [ui, setUi] = useState(function () {
10592
9782
  var style = Object.assign({}, base)
10593
9783
  if (opts.icon === true) Object.assign(style, { width: 22, minWidth: 22, padding: '1px 0', textAlign: 'center' })
10594
9784
  if (typeof opts.width === 'number') Object.assign(style, { width: opts.width, minWidth: opts.width })
9785
+ if (typeof opts.color === 'string') Object.assign(style, { color: opts.color })
10595
9786
  if (typeof opts.height === 'number') {
10596
9787
  // One fixed row height: the top bar mixes glyph buttons (📄 ⚙ ⟲) with
10597
9788
  // two-character ones (A- A+), and padding-only sizing made them differ
@@ -11647,9 +10838,6 @@ var [ui, setUi] = useState(function () {
11647
10838
  if (paneConfig !== null && typeof paneConfig.generate === 'function') {
11648
10839
  consoleConfigActions.push(button('⚙', function () { paneConfig.generate() }, { key: 'config-generate', icon: true, height: 20, action: 'config-generate', title: paneConfig.exists === true ? '更新配置:按当前扫描结果同步 .dsh-ris-ide/config.json(保留你改过的字段)' : '生成配置:把扫描到的程序写成 .dsh-ris-ide/config.json' }))
11649
10840
  }
11650
- // 「代理」: the same dialog as the sidebar console's 🌐 — the engine config
11651
- // lives per workspace (cwd), so the standalone window must offer it too.
11652
- consoleConfigActions.push(button('🌐', function () { setProxyOpen(true) }, { key: 'proxy-open', icon: true, height: 20, action: 'proxy-open', title: '代理:SOCKS 地址 + 按程序/IP/端口的规则(与侧边栏控制台共用同一份配置)' }))
11653
10841
  paneActions.push(button('⟲', resetLayout, { key: 'layout-reset', icon: true, height: 20, action: 'layout-reset', title: '还原布局尺寸:左列 300px、调试区 300px、两个下层 260px(不改变最大化状态)' }))
11654
10842
 
11655
10843
  /** Load the visual debug settings from the host (⚙ opens on a fresh read). */
@@ -11763,12 +10951,9 @@ var [ui, setUi] = useState(function () {
11763
10951
  'data-theme': themePreference || 'page',
11764
10952
  onContextMenu: function (event) { event.preventDefault() },
11765
10953
  },
11766
- proxyOpen === true
11767
- ? h(ProxyDialog, { scope: { sessionId: sessionId, cwd: cwd }, onClose: function () { setProxyOpen(false) } })
11768
- : null,
11769
10954
  // The sidebar's CodeMirror theme pins 13px, so the embedded viewer needs
11770
10955
  // this rule, not inheritance, to follow A−/A+.
11771
- h('style', { key: 'ide-font' }, viewerFontCss(uiFont) + viewerThemeCss(pageDark) + DEBUG_LINE_CSS + PREVIEW_CSS + SELECTION_CSS + SCROLLBAR_CSS + SEARCH_PANEL_CSS + TOAST_CSS + PROGRAM_LOADING_CSS),
10956
+ h('style', { key: 'ide-font' }, viewerFontCss(uiFont) + viewerThemeCss(pageDark) + DEBUG_LINE_CSS + PREVIEW_CSS + SELECTION_CSS + SCROLLBAR_CSS + SEARCH_PANEL_CSS + TOAST_CSS + PROGRAM_LOADING_CSS + TREE_HOVER_CSS),
11772
10957
  (function () {
11773
10958
  var panes = {
11774
10959
  tree: h(IdeTree, {
@@ -12228,6 +11413,7 @@ var [ui, setUi] = useState(function () {
12228
11413
  */
12229
11414
  function apply(ctx) {
12230
11415
  guardWindowErrors(false)
11416
+ watchClientBuild()
12231
11417
  if (typeof window !== 'undefined') window.__dshRisIdeWindow = false
12232
11418
  // The IDE is a DSH right-Sidebar tab: a tab TYPE (stage one) plus its body
12233
11419
  // and chip title (stage two), all through the official registry — no other
@@ -12275,16 +11461,16 @@ var [ui, setUi] = useState(function () {
12275
11461
  }, 'dsh-ris-ide: right-sidebar tab title')
12276
11462
  // A SECOND entry point for the same panel: a header button in the Session
12277
11463
  // header, immediately to the right of DSH's own "open in app" action
12278
- // (order -10), so it reads as "open this workspace's IDE". It opens the
12279
- // plugin's standalone window instead of the sidebar tab — no DSH shell, no
12280
- // session, no conversation: a window that can stay open all day.
11464
+ // (order -10), so it reads as "open this workspace's IDE". It opens the risd
11465
+ // maintenance page (which embeds the IDE and can switch workspace); when no
11466
+ // daemon is leased it falls back to the plugin's standalone window.
12281
11467
  ctx.effect(function () {
12282
11468
  return ctx.slots.inject('conversation.session.header.utilities', function () {
12283
11469
  return ctx.slots.register({
12284
11470
  name: 'conversation.session.header.utilities',
12285
11471
  id: 'ris-ide-window',
12286
11472
  order: -8,
12287
- label: function () { return '在独立窗口中打开RIS-IDE' },
11473
+ label: function () { return '打开 risd 维护页(IDE 内嵌)' },
12288
11474
  }, RisIdeWindowAction)
12289
11475
  })
12290
11476
  }, 'dsh-ris-ide: session-header window button')
@@ -12428,14 +11614,11 @@ var [ui, setUi] = useState(function () {
12428
11614
  // the single-window notice with a manual choice.
12429
11615
  await requestStandaloneWindowClose(windowName)
12430
11616
  }
12431
- // A browser cannot be told to "maximize" through window.open features, so ask
12432
- // for the screen's work area at 0,0; window.html enforces it once more on load
12433
- // in case the opener size is clamped (the OS still allows restore/resize).
12434
- var screenInfo = typeof window !== 'undefined' && window.screen !== null && window.screen !== undefined ? window.screen : null
12435
- var workWidth = screenInfo !== null && typeof screenInfo.availWidth === 'number' && screenInfo.availWidth > 0 ? screenInfo.availWidth : 1500
12436
- var workHeight = screenInfo !== null && typeof screenInfo.availHeight === 'number' && screenInfo.availHeight > 0 ? screenInfo.availHeight : 960
12437
- var features = 'popup=yes,width=' + workWidth + ',height=' + workHeight + ',left=0,top=0'
12438
- var handle = window.open(url.href, windowName, features)
11617
+ // A normal browser window/tab: no `popup=…` feature string. Asking for a popup
11618
+ // produced a chromeless window the user could not tab through or maximise like
11619
+ // every other page, and browsers ignore size hints in tabs anyway. The NAME
11620
+ // still keeps one window per workspace: re-opening the same name reuses it.
11621
+ var handle = window.open(url.href, windowName)
12439
11622
  if (handle === null || handle === undefined) {
12440
11623
  throw new Error('独立窗口被拦截:请允许本站弹窗后重试')
12441
11624
  }
@@ -12521,6 +11704,7 @@ var [ui, setUi] = useState(function () {
12521
11704
  * @param {{sessionId: string, cwd: string}} props - scope taken from the URL.
12522
11705
  * @returns {object} the panel tree.
12523
11706
  */
11707
+
12524
11708
  function StandaloneWindow(props) {
12525
11709
  var initial = props.sessionId
12526
11710
  var scopeState = useState(initial)
@@ -12564,6 +11748,7 @@ var [ui, setUi] = useState(function () {
12564
11748
  // instead of letting the browser/dsh treat them as a fatal load failure.
12565
11749
  guardWindowErrors(true)
12566
11750
  if (typeof window !== 'undefined') window.__dshRisIdeWindow = true
11751
+ watchClientBuild()
12567
11752
  var opts = options === null || options === undefined ? {} : options
12568
11753
  var sessionId = typeof opts.sessionId === 'string' && opts.sessionId !== '' ? opts.sessionId : STANDALONE_SESSION
12569
11754
  var cwd = typeof opts.cwd === 'string' && opts.cwd !== '' ? opts.cwd : knownWorkspaceCwd()
@@ -12617,6 +11802,193 @@ var [ui, setUi] = useState(function () {
12617
11802
  }
12618
11803
  }
12619
11804
 
11805
+ /** How long a prefetched daemon address stays fresh (ms). */
11806
+ var RISD_PREFETCH_TTL_MS = 20000
11807
+
11808
+ /**
11809
+ * Warm cache for the daemon address behind ⧉. The header button and the
11810
+ * sidebar console prefetch it on mount, so the click path usually only has to
11811
+ * call `window.open` — the visible delay was the on-demand spawn, but the host
11812
+ * view read is not free either and it sat in front of every click.
11813
+ *
11814
+ * A failed prefetch stays silent: the click then pays one round trip and can
11815
+ * still ask for `ensure`.
11816
+ * @type {{at: number, risd: {available: boolean, url: string}|null, pending: Promise|null}}
11817
+ */
11818
+ var risdPrefetch = { at: 0, risd: null, pending: null }
11819
+ /** The ⧉ open in flight, so a double click cannot open two tabs. */
11820
+ var risdOpenPending = null
11821
+
11822
+ /** Test seam: forget the warm cache and any open in flight. */
11823
+ function resetRisdPrefetch() {
11824
+ risdPrefetch.at = 0
11825
+ risdPrefetch.risd = null
11826
+ risdPrefetch.pending = null
11827
+ risdOpenPending = null
11828
+ }
11829
+
11830
+ /**
11831
+ * The daemon address inside a host reply, or null when it is unavailable.
11832
+ * @param {object|null} body - parsed reply from the host (`{risd: {...}}`).
11833
+ * @returns {{available: boolean, url: string}|null} the address, or null.
11834
+ */
11835
+ function risdAddressOf(body) {
11836
+ var risd = body !== null && body !== undefined ? body.risd : null
11837
+ if (risd !== null && risd !== undefined && risd.available === true && typeof risd.url === 'string' && risd.url !== '') {
11838
+ return { available: true, url: risd.url }
11839
+ }
11840
+ return null
11841
+ }
11842
+
11843
+ /**
11844
+ * The cached address while it is younger than the TTL.
11845
+ * @returns {{available: boolean, url: string}|null} the address, or null.
11846
+ */
11847
+ function risdCachedAddress() {
11848
+ if (risdPrefetch.risd === null) return null
11849
+ if (Date.now() - risdPrefetch.at >= RISD_PREFETCH_TTL_MS) return null
11850
+ return risdPrefetch.risd
11851
+ }
11852
+
11853
+ /**
11854
+ * Remember a fresh answer; the empty one is never cached.
11855
+ * @param {{available: boolean, url: string}|null} risd - the address, or null.
11856
+ * @returns {{available: boolean, url: string}|null} the same value.
11857
+ */
11858
+ function rememberRisdAddress(risd) {
11859
+ if (risd === null || risd === undefined) return null
11860
+ risdPrefetch.risd = risd
11861
+ risdPrefetch.at = Date.now()
11862
+ return risd
11863
+ }
11864
+
11865
+ /**
11866
+ * `GET /dsh-ris-ide/proxy`, reduced to the daemon address.
11867
+ * @param {{sessionId?: string, cwd?: string}} scope - owning session.
11868
+ * @returns {Promise<{available: boolean, url: string}|null>} the address, or null.
11869
+ */
11870
+ async function fetchRisdAddress(scope) {
11871
+ var url = routeUrl('dsh-ris-ide/proxy')
11872
+ var sessionId = scope !== null && scope !== undefined && typeof scope.sessionId === 'string' ? scope.sessionId : ''
11873
+ var cwd = scope !== null && scope !== undefined && typeof scope.cwd === 'string' ? scope.cwd : ''
11874
+ if (sessionId !== '') url.searchParams.set('sessionId', sessionId)
11875
+ if (cwd !== '') url.searchParams.set('cwd', cwd)
11876
+ var response = await fetch(url.href, { headers: { accept: 'application/json' } })
11877
+ var body = await response.json().catch(function () { return null })
11878
+ return risdAddressOf(body)
11879
+ }
11880
+
11881
+ /**
11882
+ * The daemon address, from the warm cache when possible.
11883
+ *
11884
+ * In-flight requests are shared, so two mounts (header + console) cost one
11885
+ * request. Failures are silent: the click path falls back to `ensure`.
11886
+ * @param {{sessionId?: string, cwd?: string}} scope - owning session.
11887
+ * @returns {Promise<{available: boolean, url: string}|null>} the address, or null.
11888
+ */
11889
+ function prefetchRisd(scope) {
11890
+ var cached = risdCachedAddress()
11891
+ if (cached !== null) return Promise.resolve(cached)
11892
+ if (risdPrefetch.pending !== null) return risdPrefetch.pending
11893
+ var pending = fetchRisdAddress(scope).then(function (risd) {
11894
+ risdPrefetch.pending = null
11895
+ return rememberRisdAddress(risd)
11896
+ }, function () {
11897
+ risdPrefetch.pending = null
11898
+ return null
11899
+ })
11900
+ risdPrefetch.pending = pending
11901
+ return pending
11902
+ }
11903
+
11904
+ /**
11905
+ * Put the maintenance page in its tab, on the IDE view, then focus it.
11906
+ *
11907
+ * Called synchronously from the click when the address is already cached, so
11908
+ * the popup stays inside the user gesture (browsers only allow it there).
11909
+ * @param {{url: string}} risd - the daemon address.
11910
+ * @param {string} cwd - workspace to preselect ('' = the daemon's own choice).
11911
+ * @returns {Window} the opened tab.
11912
+ * @throws {Error} when the browser blocked the popup.
11913
+ */
11914
+ function openRisdTab(risd, cwd) {
11915
+ // Preselect this workspace but keep the user's own tab: ⧉ says "open the
11916
+ // maintenance page for this workspace", not "switch me to 开发环境" (m11345).
11917
+ // The page remembers the last tab, so an explicit `tab=` here would override
11918
+ // that choice and feel like a menu switch.
11919
+ var query = cwd !== '' ? '?cwd=' + encodeURIComponent(cwd) : ''
11920
+ var target = risd.url + '/ui' + query
11921
+ var handle = window.open(target, 'dsh-risd-ui')
11922
+ if (handle === null) throw new Error('维护页被拦截:请允许本站弹窗后重试')
11923
+ if (typeof handle.focus === 'function') handle.focus()
11924
+ return handle
11925
+ }
11926
+
11927
+ /**
11928
+ * Open the risd maintenance page, which embeds the IDE (and can switch
11929
+ * workspace), instead of spawning one window per workspace.
11930
+ *
11931
+ * The page lives on the daemon origin, so the client cannot guess it: the
11932
+ * host view (`GET /dsh-ris-ide/proxy`) reports `risd.url` while a daemon is
11933
+ * leased — prefetched on mount (see `prefetchRisd`), so ⧉ normally opens
11934
+ * without waiting. A cold click asks the host once and then `ensure`s the
11935
+ * daemon; when daemonMode is off (or the daemon stays unreachable) the
11936
+ * fallback keeps today's behaviour — the standalone window.
11937
+ *
11938
+ * One open at a time: a second click joins the promise in flight instead of
11939
+ * opening a second tab.
11940
+ * @param {{sessionId?: string, cwd?: string}} scope - owning session.
11941
+ * @param {Function} fallback - opens the standalone window when no daemon.
11942
+ * @returns {Promise<'risd'|'window'>} which entry point was used.
11943
+ */
11944
+ async function openRisdPage(scope, fallback) {
11945
+ var cwd = scope !== null && scope !== undefined && typeof scope.cwd === 'string' ? scope.cwd : ''
11946
+ var sessionId = scope !== null && scope !== undefined && typeof scope.sessionId === 'string' ? scope.sessionId : ''
11947
+ if (risdOpenPending !== null) return risdOpenPending
11948
+ var cached = risdCachedAddress()
11949
+ if (cached !== null) {
11950
+ // No await before the popup: the cached address is the whole answer.
11951
+ openRisdTab(cached, cwd)
11952
+ return 'risd'
11953
+ }
11954
+ var pending = openRisdPageSlow({ sessionId: sessionId, cwd: cwd }, fallback).then(function (result) {
11955
+ risdOpenPending = null
11956
+ return result
11957
+ }, function (error) {
11958
+ risdOpenPending = null
11959
+ throw error
11960
+ })
11961
+ risdOpenPending = pending
11962
+ return pending
11963
+ }
11964
+
11965
+ /**
11966
+ * The cold half of `openRisdPage`: one host round trip, then `ensure`.
11967
+ * @param {{sessionId: string, cwd: string}} scope - owning session.
11968
+ * @param {Function} fallback - opens the standalone window when no daemon.
11969
+ * @returns {Promise<'risd'|'window'>} which entry point was used.
11970
+ */
11971
+ async function openRisdPageSlow(scope, fallback) {
11972
+ var risd = null
11973
+ try {
11974
+ risd = await prefetchRisd(scope)
11975
+ if (risd === null) {
11976
+ // Stopped or crashed: clicking ⧉ is also the "bring it back" gesture, so
11977
+ // ask the host to spawn the daemon on demand instead of silently falling
11978
+ // back to the old standalone window.
11979
+ var response = await fetch(routeUrl('dsh-ris-ide/risd/ensure').href, { method: 'POST' })
11980
+ var body = await response.json().catch(function () { return null })
11981
+ risd = rememberRisdAddress(risdAddressOf(body))
11982
+ }
11983
+ } catch { /* daemonMode=off or host unreachable: fall back to the window */ }
11984
+ if (risd !== null) {
11985
+ openRisdTab(risd, scope.cwd)
11986
+ return 'risd'
11987
+ }
11988
+ if (typeof fallback === 'function') await fallback()
11989
+ return 'window'
11990
+ }
11991
+
12620
11992
  /**
12621
11993
  * Session-header action: open the IDE in its own window.
12622
11994
  *
@@ -12637,34 +12009,56 @@ var [ui, setUi] = useState(function () {
12637
12009
  var sessionId = props !== null && props !== undefined && typeof props.sessionId === 'string' ? props.sessionId : ''
12638
12010
  var sessionCwd = sessionWorkspaceCwd(props !== null && props !== undefined ? props.useSessions : undefined, sessionId)
12639
12011
  var [blocked, setBlocked] = useState(false)
12012
+ var [opening, setOpening] = useState(false)
12640
12013
  useEffect(function () {
12641
12014
  if (blocked !== true) return undefined
12642
12015
  var timer = setTimeout(function () { setBlocked(false) }, 4000)
12643
12016
  return function () { clearTimeout(timer) }
12644
12017
  }, [blocked])
12018
+ /** Warm the daemon address; `prefetchRisd` is a no-op while the cache is fresh. */
12019
+ function warmRisdAddress() {
12020
+ void prefetchRisd({ sessionId: sessionId, cwd: sessionCwd })
12021
+ }
12022
+ useEffect(function () {
12023
+ // Warm the daemon address before the click; ⧉ then opens without a wait.
12024
+ warmRisdAddress()
12025
+ }, [sessionId, sessionCwd])
12645
12026
  if (blocked === true) {
12646
12027
  return h('span', { style: S.windowButtonError, role: 'status', title: '允许本站弹窗后重试' }, '窗口被拦截')
12647
12028
  }
12648
12029
  async function onClick(event) {
12649
12030
  if (event !== undefined && typeof event.preventDefault === 'function') event.preventDefault()
12031
+ if (opening === true) return
12032
+ setOpening(true)
12650
12033
  try {
12651
- var handle = await openStandaloneWindow({ sessionId: sessionId, cwd: sessionCwd, windowCwd: sessionCwd })
12652
- if (handle !== null && handle !== undefined && typeof handle.focus === 'function') handle.focus()
12034
+ await openRisdPage({ sessionId: sessionId, cwd: sessionCwd }, async function () {
12035
+ var handle = await openStandaloneWindow({ sessionId: sessionId, cwd: sessionCwd, windowCwd: sessionCwd })
12036
+ if (handle !== null && handle !== undefined && typeof handle.focus === 'function') handle.focus()
12037
+ })
12653
12038
  } catch (error) {
12654
12039
  console.warn('dsh-ris-ide: 独立窗口打开失败:' + messageOf(error))
12655
12040
  setBlocked(true)
12041
+ } finally {
12042
+ setOpening(false)
12656
12043
  }
12657
12044
  }
12658
12045
  return h('button', {
12659
12046
  type: 'button',
12660
- style: S.windowButton,
12661
- title: '在独立窗口中打开RIS-IDE',
12662
- 'aria-label': '在独立窗口中打开RIS-IDE',
12047
+ style: opening === true ? Object.assign({}, S.windowButton, { opacity: 0.62, cursor: 'default' }) : S.windowButton,
12048
+ disabled: opening === true,
12049
+ 'aria-busy': opening === true ? 'true' : 'false',
12050
+ title: opening === true ? '正在打开 risd 维护页…' : '打开 risd 维护页(概览 / 代理 / IDE):IDE 内嵌其中,可按工作区切换',
12051
+ 'aria-label': opening === true ? '正在打开 risd 维护页' : '打开 risd 维护页(IDE 内嵌,可按工作区切换)',
12663
12052
  'data-action': 'ris-ide-window',
12053
+ // Pointer intent is the earliest reliable "about to click" signal: the
12054
+ // address is usually already cached from mount, and this covers a stale
12055
+ // 20 s window without waiting for the click itself.
12056
+ onPointerEnter: warmRisdAddress,
12057
+ onFocus: warmRisdAddress,
12664
12058
  onClick: onClick,
12665
12059
  },
12666
- h('span', { style: S.windowButtonIcon, 'aria-hidden': 'true' }, '⧉'),
12667
- h('span', null, 'RIS-IDE'))
12060
+ h('span', { style: S.windowButtonIcon, 'aria-hidden': 'true' }, opening === true ? '…' : '⧉'),
12061
+ h('span', null, opening === true ? '打开中' : 'RIS-IDE'))
12668
12062
  }
12669
12063
 
12670
12064
  /**
@@ -14339,8 +13733,6 @@ var [ui, setUi] = useState(function () {
14339
13733
  * already delivered: the log viewer re-reads the tail once (see `reloadNonce`).
14340
13734
  */
14341
13735
  var [compactLogNonce, setCompactLogNonce] = useState(0)
14342
- /** The 「代理」 dialog: address + rule table, shared by both console shapes. */
14343
- var [compactProxyOpen, setCompactProxyOpen] = useState(false)
14344
13736
  useEffect(function () {
14345
13737
  if (pendingProgram === null) return undefined
14346
13738
  setActive(pendingProgram)
@@ -14404,6 +13796,19 @@ var [ui, setUi] = useState(function () {
14404
13796
  setCompactPick(undefined)
14405
13797
  setActive(undefined)
14406
13798
  }, [sessionIdentity])
13799
+ /** Warm the compact ⧉'s address; a fresh cache makes the click synchronous. */
13800
+ function warmCompactRisd() {
13801
+ if (typeof sessionId !== 'string' || sessionId === '') return
13802
+ void prefetchRisd({ sessionId: sessionId, cwd: cwd })
13803
+ }
13804
+ useEffect(function () {
13805
+ // The compact ⧉ shares the header button's warm cache: prefetch while the
13806
+ // user is reading the panel, so the click only has to open the tab. The
13807
+ // host view needs a session id, so a tab whose session is not known yet
13808
+ // waits for the live one instead of earning a 400.
13809
+ warmCompactRisd()
13810
+ return undefined
13811
+ }, [sessionIdentity])
14407
13812
  // COMPACT mode is the sidebar panel: console rows on top, ONE program's
14408
13813
  // live log below. The full IDE (tree/editor/debug) lives only in the
14409
13814
  // standalone window, so the sidebar stays cheap and readable.
@@ -14452,6 +13857,8 @@ var [ui, setUi] = useState(function () {
14452
13857
  }, [state.note])
14453
13858
 
14454
13859
  var [busyId, setBusyId] = useState(undefined)
13860
+ /** The compact ⧉ is opening the page: disable it and show progress. */
13861
+ var [openingIde, setOpeningIde] = useState(false)
14455
13862
  /** Which action `busyId` is running, for the row mask's wording. */
14456
13863
  var [busyKind, setBusyKind] = useState('')
14457
13864
  var busyRef = useRef(false)
@@ -14818,16 +14225,22 @@ var [ui, setUi] = useState(function () {
14818
14225
 
14819
14226
  /** Open the standalone window on the picked program (or on the workspace). */
14820
14227
  function openCompactWindow() {
14228
+ if (openingIde === true) return
14821
14229
  var picked = compactProgram()
14230
+ setOpeningIde(true)
14822
14231
  void (async function () {
14823
14232
  try {
14824
- // One window per workspace: a second click on ⧉ must focus the IDE the
14825
- // user already has (the registry knows), never open a twin.
14826
- var handle = await openStandaloneWindow({ sessionId: sessionId, cwd: cwd, programId: picked !== undefined ? picked.id : undefined })
14827
- if (handle !== null && handle !== undefined && typeof handle.focus === 'function') handle.focus()
14828
- else setState(function (prev) { return Object.assign({}, prev, { note: '已切到本工作空间的 IDE 窗口' }) })
14233
+ // Prefer the risd maintenance page (one tab, all workspaces). Without a
14234
+ // daemon, keep the one-window-per-workspace behaviour.
14235
+ await openRisdPage({ sessionId: sessionId, cwd: cwd }, async function () {
14236
+ var handle = await openStandaloneWindow({ sessionId: sessionId, cwd: cwd, programId: picked !== undefined ? picked.id : undefined })
14237
+ if (handle !== null && handle !== undefined && typeof handle.focus === 'function') handle.focus()
14238
+ else setState(function (prev) { return Object.assign({}, prev, { note: '已切到本工作空间的 IDE 窗口' }) })
14239
+ })
14829
14240
  } catch (error) {
14830
14241
  setState(function (prev) { return Object.assign({}, prev, { note: '打开 IDE 窗口失败:' + messageOf(error) }) })
14242
+ } finally {
14243
+ setOpeningIde(false)
14831
14244
  }
14832
14245
  })()
14833
14246
  }
@@ -14994,9 +14407,6 @@ var [ui, setUi] = useState(function () {
14994
14407
  }
14995
14408
  return h('div', { ref: rootRef, style: S.root, 'data-panel': 'compact' },
14996
14409
  h('style', { key: 'compact-loading-css' }, PROGRAM_LOADING_CSS),
14997
- compactProxyOpen === true
14998
- ? h(ProxyDialog, { scope: { sessionId: sessionId, cwd: cwd }, onClose: function () { setCompactProxyOpen(false) } })
14999
- : null,
15000
14410
  h('div', { style: S.bar, 'data-compact-bar': '1' },
15001
14411
  h('span', { style: S.status }, state.loading ? '扫描中…' : (state.programs.length + ' 个项目')),
15002
14412
  h('span', { style: S.meta, title: state.root }, state.root || ''),
@@ -15004,11 +14414,6 @@ var [ui, setUi] = useState(function () {
15004
14414
  // The config actions live on the CONSOLE title bar in both shapes: the
15005
14415
  // sidebar's title bar is this top bar, so it gets the same two icons
15006
14416
  // the standalone window puts next to its program list.
15007
- h('button', {
15008
- type: 'button', style: S.paneIcon, 'data-action': 'compact-proxy',
15009
- title: '代理:上游 SOCKS 地址 + 规则(程序 · IP 允许 · 端口)。整机生效;能配代理的程序由 ProxyBridge 按进程拦截,只能填 host:port 的客户端自动用 127.0.0.1 同端口映射',
15010
- onClick: function () { setCompactProxyOpen(true) },
15011
- }, '🌐'),
15012
14417
  configExists === true
15013
14418
  ? h('button', {
15014
14419
  type: 'button', style: S.paneIcon, 'data-action': 'compact-config-open',
@@ -15025,10 +14430,23 @@ var [ui, setUi] = useState(function () {
15025
14430
  onClick: function () { generateConfigFile(configExists ? 'update' : undefined) },
15026
14431
  }, busyId === '__config__' ? '…' : '⚙'),
15027
14432
  h('button', {
15028
- type: 'button', style: S.paneButton, 'data-action': 'ide-window',
15029
- title: '在独立窗口中打开RIS-IDE' + (picked !== undefined ? ':' + picked.name : ''),
14433
+ type: 'button',
14434
+ style: openingIde === true ? Object.assign({}, S.paneButton, { opacity: 0.62, cursor: 'default' }) : S.paneButton,
14435
+ disabled: openingIde === true,
14436
+ 'aria-busy': openingIde === true ? 'true' : 'false',
14437
+ 'data-action': 'ide-window',
14438
+ title: openingIde === true
14439
+ ? '正在打开 risd 维护页…'
14440
+ : '打开 risd 维护页(IDE 内嵌,可按工作区切换)' + (picked !== undefined ? ':' + picked.name : ''),
14441
+ // Icon only: the console title bar is tight, and the ⧉ is already the
14442
+ // IDE's mark everywhere else in the panel (aria-label keeps the text).
14443
+ 'aria-label': openingIde === true
14444
+ ? '正在打开 risd 维护页'
14445
+ : '打开 risd 维护页(IDE 内嵌)' + (picked !== undefined ? ':' + picked.name : ''),
14446
+ onPointerEnter: warmCompactRisd,
14447
+ onFocus: warmCompactRisd,
15030
14448
  onClick: openCompactWindow,
15031
- }, '⧉ IDE'),
14449
+ }, openingIde === true ? '…' : '⧉'),
15032
14450
  h('button', {
15033
14451
  type: 'button', style: state.loading ? S.paneIconOff : S.paneIcon,
15034
14452
  disabled: state.loading, 'data-action': 'compact-rescan',
@@ -15165,7 +14583,12 @@ var [ui, setUi] = useState(function () {
15165
14583
 
15166
14584
  if (compact) return compactPanel()
15167
14585
 
14586
+ // key = workspaceKey: the tabs, recent list and layout of the workbench are
14587
+ // initialised from that workspace's own blob at mount, so a cwd change has to
14588
+ // remount instead of keeping the previous workspace's state (评审
14589
+ // 20261109-2326 客户端 P2).
15168
14590
  return h(ProgramWorkbench, {
14591
+ key: typeof cwd === 'string' && cwd !== '' ? cwd : 'default',
15169
14592
  scope: { sessionId: sessionId, cwd: cwd },
15170
14593
  visible: true,
15171
14594
  programs: state.programs,
@@ -15355,13 +14778,21 @@ var [ui, setUi] = useState(function () {
15355
14778
  standaloneWindowName: standaloneWindowName,
15356
14779
  STANDALONE_SESSION: STANDALONE_SESSION,
15357
14780
  openInstanceLog: openInstanceLog,
14781
+ // The risd page opener: the prefetch cache, the address picker and the
14782
+ // open-at-most-once guard are what keep ⧉ from waiting (and from opening
14783
+ // two tabs); the tests drive them against a fake fetch/window.
14784
+ openRisdPage: openRisdPage,
14785
+ prefetchRisd: prefetchRisd,
14786
+ risdCachedAddress: risdCachedAddress,
14787
+ risdAddressOf: risdAddressOf,
14788
+ resetRisdPrefetch: resetRisdPrefetch,
14789
+ RISD_PREFETCH_TTL_MS: RISD_PREFETCH_TTL_MS,
15358
14790
  requestStart: requestStart,
15359
14791
  generateConfig: generateConfig,
15360
14792
  drainOpenRequests: drainOpenRequests,
15361
14793
  ProgramWorkbench: ProgramWorkbench,
15362
14794
  ProgramsPanel: ProgramsPanel,
15363
14795
  // Proxy dialog (address + rule table), rendered from both console shapes.
15364
- ProxyDialog: ProxyDialog,
15365
14796
  IdeErrorBoundary: IdeErrorBoundary,
15366
14797
  PROGRAM_TAB_ID: PROGRAM_TAB_ID,
15367
14798
  // The compact sidebar shape: its default log-pane height (240px) and the