dsh-ris-ide 1.7.2 → 1.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -179,6 +179,101 @@ window.__ModuleLoader__.load({
179
179
  return knownWorkspaceCwd()
180
180
  }
181
181
 
182
+ /**
183
+ * The workspace of ONE session, read through the slot's standard `useSessions`
184
+ * hook.
185
+ *
186
+ * Every slot entry receives `useSessions` (the session store) and, inside a
187
+ * session-scoped slot, that session's `sessionId`. Asking the store is the only
188
+ * way to learn the CURRENT session's workspace: `knownWorkspaceCwd()` is
189
+ * whatever the last host answer happened to mention, i.e. possibly the
190
+ * PREVIOUS session's workspace. A missing hook (an older host, the standalone
191
+ * window page, a bare render) or an unknown session answers `undefined`, so
192
+ * callers keep their own fallback.
193
+ * @param {Function|undefined} useSessions - standard slot prop, `useSessions(select)`.
194
+ * @param {string} sessionId - this session's id.
195
+ * @returns {string|undefined} the session's workspace path.
196
+ */
197
+ function sessionWorkspaceCwd(useSessions, sessionId) {
198
+ if (typeof useSessions !== 'function' || typeof sessionId !== 'string' || sessionId === '') return undefined
199
+ return useSessions(function (state) {
200
+ var rows = state !== null && state !== undefined ? state.byId : undefined
201
+ var row = rows !== null && rows !== undefined && typeof rows === 'object' ? rows[sessionId] : undefined
202
+ var cwd = row !== null && row !== undefined ? row.cwd : undefined
203
+ return typeof cwd === 'string' && cwd !== '' ? cwd : undefined
204
+ })
205
+ }
206
+
207
+ /**
208
+ * Which Session the right Sidebar is drawn for RIGHT NOW, read from the DOM.
209
+ *
210
+ * `keepMounted: true` deliberately keeps a visited tab body alive "through
211
+ * hiding, Session changes and docking", so its props keep the session it was
212
+ * OPENED in. Switching workspace then left the console listing the previous
213
+ * project. DSH already marks the live one for its own focus logic
214
+ * (`data-sidebar-right-session`), and reading that attribute needs no extra
215
+ * plugin dependency and no host round trip.
216
+ * @returns {string|undefined} the live session id, or undefined off-DOM.
217
+ */
218
+ /**
219
+ * The Session whose right Sidebar is on screen right now.
220
+ *
221
+ * The tab body outlives Session switches (`keepMounted`), so its injected
222
+ * `sessionId` keeps naming the Session it was opened in. The sidebar marks
223
+ * its DOM with `data-sidebar-right-session`: the panel element carries the
224
+ * live Session, while retained `SessionView` wrappers each carry their own
225
+ * and sit hidden. Taking the first match therefore returns a stale hidden
226
+ * wrapper, so the panel is preferred and visibility is required.
227
+ * @returns the live Session id, or undefined when no sidebar is mounted.
228
+ */
229
+ function liveSidebarSessionId(origin) {
230
+ if (typeof document === 'undefined') return undefined
231
+ /**
232
+ * Whether the marker sits in what the reader can see right now.
233
+ * @param {Element} node - element carrying `data-sidebar-right-session`.
234
+ * @returns {boolean} true when it is rendered and not inside a hidden tree.
235
+ */
236
+ function shown(node) {
237
+ if (node.hidden === true) return false
238
+ if (typeof node.closest === 'function' && node.closest('[hidden]') !== null) return false
239
+ if (typeof node.getClientRects === 'function' && node.getClientRects().length === 0) return false
240
+ return true
241
+ }
242
+ /**
243
+ * @param {Element|undefined} node - candidate marker.
244
+ * @returns {string|undefined} its Session id.
245
+ */
246
+ function valueOf(node) {
247
+ if (node === null || node === undefined || typeof node.getAttribute !== 'function') return undefined
248
+ var value = node.getAttribute('data-sidebar-right-session')
249
+ return typeof value === 'string' && value !== '' ? value : undefined
250
+ }
251
+ // 1. The body's own ancestor, when it is on screen: DSH re-parents a retained
252
+ // tab body into the Session that is showing now, so this is the truth.
253
+ if (origin !== null && origin !== undefined && typeof origin.closest === 'function') {
254
+ var nearest = origin.closest('[data-sidebar-right-session]')
255
+ var nearestId = valueOf(nearest)
256
+ if (nearestId !== undefined && shown(nearest)) return nearestId
257
+ }
258
+ if (typeof document.querySelectorAll !== 'function') return undefined
259
+ // 2. Otherwise the sidebar PANEL element, which always names the live
260
+ // Session, then any other visible marker (a floating pane inside a
261
+ // SessionView). Retained wrappers are hidden, so they never win here.
262
+ var nodes = document.querySelectorAll('[data-sidebar-right-session]')
263
+ var fallback
264
+ for (var i = 0; i < nodes.length; i += 1) {
265
+ var node = nodes[i]
266
+ var value = valueOf(node)
267
+ if (value === undefined) continue
268
+ if (!shown(node)) continue
269
+ if (typeof node.hasAttribute === 'function' && node.hasAttribute('data-sidebar-right-panel')) return value
270
+ if (fallback === undefined) fallback = value
271
+ }
272
+ // 3. Nothing visible (collapsed sidebar): no opinion, the caller keeps its
273
+ // last good answer rather than falling back to the stale injected one.
274
+ return fallback
275
+ }
276
+
182
277
  /**
183
278
  * The log pane of ONE plugin instance (sidebar console or standalone window)
184
279
  * has no idea that another instance just started/debugged a program. A storage
@@ -1129,6 +1224,16 @@ window.__ModuleLoader__.load({
1129
1224
  var PREF_FONT_SIZE = 'dsh-ris-ide.fontSize'
1130
1225
  /** The theme's mono token first, then what a Linux desktop actually has. */
1131
1226
  var MONO_FAMILY = "var(--dsw-font-mono, 'Ubuntu Sans Mono', 'Ubuntu Mono', 'JetBrains Mono', 'Fira Code', 'Noto Sans Mono', 'DejaVu Sans Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace)"
1227
+ /**
1228
+ * The chrome font the IDE window renders with.
1229
+ *
1230
+ * The IDE page defines `--dsw-font-mono` (this theme maps it to a system UI
1231
+ * stack), but the DSH sidebar does not, so a sidebar dialog that repeated the
1232
+ * mono list fell back to a real monospace face and measured wider than the
1233
+ * same dialog in the IDE window — rule rows wrapped only in the sidebar. The
1234
+ * fallback is therefore the stack the token resolves to, not a mono list.
1235
+ */
1236
+ var CHROME_FAMILY = "var(--dsw-font-mono, system-ui, -apple-system, 'Segoe UI', 'Microsoft YaHei', sans-serif)"
1132
1237
 
1133
1238
  var BASE_STYLES = {
1134
1239
  root: {
@@ -1789,6 +1894,1086 @@ window.__ModuleLoader__.load({
1789
1894
  /** The unscaled set: components outside the IDE (the sidebar's own viewers). */
1790
1895
  var S = stylesFor(1)
1791
1896
 
1897
+ /**
1898
+ * The 「代理」 dialog: the upstream SOCKS address on top, the rule table below.
1899
+ *
1900
+ * Rules are the contract with the engine (`lib/proxy.js`): each row names a
1901
+ * PROGRAM (display only for now), an IP allow-list (`1.1.1.*`, comma lists) and
1902
+ * a PORT allow-list (`5432`, `1000-1010`). An empty host or port cell means
1903
+ * "this axis is unrestricted", which the host route reports back so the table
1904
+ * can colour the row instead of silently allowing the world.
1905
+ *
1906
+ * Editing is local until 保存: the engine keeps its listeners until restarted,
1907
+ * so the dialog says so out loud instead of pretending a save took effect.
1908
+ */
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
+
1792
2977
  /** Scaled CSS for viewers that paint their own font (CodeMirror pins 13px). */
1793
2978
  function viewerFontCss(size) {
1794
2979
  return '[data-workbench="ris-ide"] .cm-editor{font-size:' + size + 'px !important}'
@@ -6311,7 +7496,12 @@ window.__ModuleLoader__.load({
6311
7496
  var findInput = findInputRef.current
6312
7497
  if (findInput !== null && findInput !== undefined) {
6313
7498
  findInput.focus()
6314
- if (typeof findInput.select === 'function') findInput.select()
7499
+ // Caret at the END, never a selection: the bar searches on every
7500
+ // keystroke below, and a selected term would be replaced by the first
7501
+ // one (the same bug the CodeMirror panel had).
7502
+ if (typeof findInput.setSelectionRange === 'function') {
7503
+ findInput.setSelectionRange(findInput.value.length, findInput.value.length)
7504
+ }
6315
7505
  }
6316
7506
  return
6317
7507
  }
@@ -7087,6 +8277,8 @@ window.__ModuleLoader__.load({
7087
8277
  })
7088
8278
  }
7089
8279
  function ProgramWorkbench(props) {
8280
+ /** The 「代理」 dialog (address + rule table); see `ProxyDialog`. */
8281
+ var [proxyOpen, setProxyOpen] = useState(false)
7090
8282
  var scope = props ? props.scope : undefined
7091
8283
  var tab = props ? props.tab : undefined
7092
8284
  var meta = tab !== null && tab !== undefined && tab.meta !== null && typeof tab.meta === 'object' ? tab.meta : {}
@@ -7188,6 +8380,13 @@ var [ui, setUi] = useState(function () {
7188
8380
  * query (or the `git grep` output) away, so the same row can be reopened.
7189
8381
  */
7190
8382
  var searchCacheRef = useRef(new Map())
8383
+ /**
8384
+ * Bumped when the cached results for the CURRENT query must be thrown away
8385
+ * (Ctrl+R, or a save in this window). `searchCacheRef` is keyed by query text
8386
+ * only, while its payload is `git grep` output captured at one moment — so
8387
+ * without a kick an edited file kept showing the old hits forever.
8388
+ */
8389
+ var [searchReload, setSearchReload] = useState(0)
7191
8390
  /** A shortcut asked for the box: focus AND select its text once mounted. */
7192
8391
  var [searchFocusNonce, setSearchFocusNonce] = useState(0)
7193
8392
  var searchFocusPendingRef = useRef(false)
@@ -7681,8 +8880,6 @@ var [ui, setUi] = useState(function () {
7681
8880
  }
7682
8881
  return String(logPathValue).split('/').pop().replace(/\.log$/, '')
7683
8882
  }
7684
- /** Basename of a file path. */
7685
- function shortName(path) { return String(path === undefined || path === null ? '' : path).split('/').pop() }
7686
8883
 
7687
8884
  // The debug/log target follows the SELECTED debug tab, not "the first
7688
8885
  // program": the workbench is workspace-level, several programs coexist.
@@ -8086,7 +9283,7 @@ var [ui, setUi] = useState(function () {
8086
9283
  }
8087
9284
  var next = capOpenFiles(openFiles, path, FILE_LIMIT, isDirty)
8088
9285
  if (next === null) {
8089
- note('已打开 ' + FILE_LIMIT + ' 个文件且都有未保存修改,请先关闭一个再打开 ' + shortName(path))
9286
+ note('已打开 ' + FILE_LIMIT + ' 个文件且都有未保存修改,请先关闭一个再打开 ' + fileBaseName(path))
8090
9287
  return
8091
9288
  }
8092
9289
  // A path that is NOT already open must be read from disk: a document or
@@ -8109,7 +9306,7 @@ var [ui, setUi] = useState(function () {
8109
9306
  if (request === null || typeof request !== 'object') return
8110
9307
  if (typeof request.path !== 'string' || request.path === '') return
8111
9308
  openPath(request.path)
8112
- note('已在编辑器打开 ' + shortName(request.path) + '(改完保存即生效)')
9309
+ note('已在编辑器打开 ' + fileBaseName(request.path) + '(改完保存即生效)')
8113
9310
  }, [configOpenNonce])
8114
9311
  function closePath(path) {
8115
9312
  debugOpenedRef.current = debugOpenedRef.current.filter(function (item) { return item !== path })
@@ -8133,7 +9330,7 @@ var [ui, setUi] = useState(function () {
8133
9330
  setRecentFiles(function (previous) {
8134
9331
  return previous.filter(function (item) { return item !== path })
8135
9332
  })
8136
- note('文件不存在,已从最近历史移除:' + shortName(path))
9333
+ note('文件不存在,已从最近历史移除:' + fileBaseName(path))
8137
9334
  return
8138
9335
  }
8139
9336
  openPath(path)
@@ -8161,6 +9358,9 @@ var [ui, setUi] = useState(function () {
8161
9358
  if (doc === undefined || doc.kind !== 'text') return Promise.resolve(true)
8162
9359
  setSavingPath(path)
8163
9360
  return fsWrite(scopeRef.current, path, docTextForDisk(doc)).then(function () {
9361
+ // The file on disk just changed, so any cached `git grep` payload for the
9362
+ // query in the box is stale; refresh it (a no-op when nothing is cached).
9363
+ reloadWorkspaceSearch(treeQuery)
8164
9364
  setDocs(function (prev) {
8165
9365
  var next = Object.assign({}, prev)
8166
9366
  var current = next[path]
@@ -8219,7 +9419,7 @@ var [ui, setUi] = useState(function () {
8219
9419
  try {
8220
9420
  await fsWrite(scopeRef.current, path, docTextForDisk(doc))
8221
9421
  } catch (problem) {
8222
- note('保存失败:' + shortName(path) + ' ' + messageOf(problem))
9422
+ note('保存失败:' + fileBaseName(path) + ' ' + messageOf(problem))
8223
9423
  return false
8224
9424
  }
8225
9425
  setDocs(function (previous) {
@@ -8955,6 +10155,30 @@ var [ui, setUi] = useState(function () {
8955
10155
  return function () { window.removeEventListener('mousedown', onDown); window.removeEventListener('keydown', onKey) }
8956
10156
  }, [tabMenu])
8957
10157
 
10158
+ /**
10159
+ * Re-reads the workspace for the current query instead of replaying the cache.
10160
+ *
10161
+ * `searchCacheRef` holds `git grep`/name-search payloads keyed by the query
10162
+ * TEXT, and it is what lets a picked row be reopened without re-running the
10163
+ * search. The price is that file contents are not part of the key: after an
10164
+ * edit the same query kept returning the old hits (reported bug). Any
10165
+ * explicit "search again" — Ctrl+R or a save in this window — drops the two
10166
+ * entries for the query and bumps `searchReload`, which the effects depend on.
10167
+ * @param {string} [text] - the query to refresh; defaults to the box's value.
10168
+ */
10169
+ function reloadWorkspaceSearch(text) {
10170
+ var raw = typeof text === 'string' ? text : treeQuery
10171
+ var query = String(raw === undefined || raw === null ? '' : raw).trim()
10172
+ var dropped = false
10173
+ if (query !== '') {
10174
+ dropped = searchCacheRef.current.delete('content:' + query) || dropped
10175
+ dropped = searchCacheRef.current.delete('name:' + query) || dropped
10176
+ }
10177
+ // Nothing cached: whatever is on screen came from a run that is still
10178
+ // fresh (or is already in flight), so a second kick would only abort it.
10179
+ if (dropped) setSearchReload(function (value) { return value + 1 })
10180
+ }
10181
+
8958
10182
  /** Toolbar search: debounce, then stream matches page by page from the host route. */
8959
10183
  useEffect(function () {
8960
10184
  var text = treeQuery.trim()
@@ -8996,7 +10220,7 @@ var [ui, setUi] = useState(function () {
8996
10220
  clearTimeout(timer)
8997
10221
  if (controller !== null) controller.abort()
8998
10222
  }
8999
- }, [treeQuery, cwd])
10223
+ }, [treeQuery, cwd, searchReload])
9000
10224
 
9001
10225
  /**
9002
10226
  * Content search for the same query: slower than the name search (one
@@ -9041,12 +10265,17 @@ var [ui, setUi] = useState(function () {
9041
10265
  clearTimeout(timer)
9042
10266
  if (controller !== null) controller.abort()
9043
10267
  }
9044
- }, [treeQuery, cwd])
10268
+ }, [treeQuery, cwd, searchReload])
9045
10269
 
9046
10270
  /**
9047
10271
  * A shortcut (Ctrl+R / Ctrl+Shift+R / F3) focused the box: select its text
9048
10272
  * once React has painted the value, otherwise the controlled update resets
9049
10273
  * the selection to the end and the highlight the user asked for is lost.
10274
+ *
10275
+ * The same shortcut is also the user's "search again" gesture (the standalone
10276
+ * window never lets it reload the page), so it re-reads the workspace: the
10277
+ * query text did not change, and without this the cache would replay the hits
10278
+ * from before the file was edited.
9050
10279
  */
9051
10280
  useEffect(function () {
9052
10281
  if (searchFocusPendingRef.current !== true) return
@@ -9055,6 +10284,7 @@ var [ui, setUi] = useState(function () {
9055
10284
  searchFocusPendingRef.current = false
9056
10285
  input.focus()
9057
10286
  input.select()
10287
+ reloadWorkspaceSearch(treeQuery)
9058
10288
  }, [searchFocusNonce, treeQuery])
9059
10289
 
9060
10290
  /**
@@ -9696,7 +10926,7 @@ var [ui, setUi] = useState(function () {
9696
10926
  scope: scopeRef.current,
9697
10927
  path: path,
9698
10928
  fontRatio: fontRatio,
9699
- title: shortName(path),
10929
+ title: fileBaseName(path),
9700
10930
  text: doc.text,
9701
10931
  savedText: doc.saved,
9702
10932
  onEditorMenu: setEditorMenu,
@@ -9762,7 +10992,7 @@ var [ui, setUi] = useState(function () {
9762
10992
  } else if (/\.html?$/i.test(openFile)) {
9763
10993
  content = h('iframe', {
9764
10994
  style: S.previewFrame, sandbox: '', srcDoc: doc.text,
9765
- title: 'HTML 预览:' + shortName(openFile), 'data-preview-frame': '1',
10995
+ title: 'HTML 预览:' + fileBaseName(openFile), 'data-preview-frame': '1',
9766
10996
  })
9767
10997
  } else {
9768
10998
  content = h('div', {
@@ -9791,8 +11021,8 @@ var [ui, setUi] = useState(function () {
9791
11021
  type: 'button', style: Object.assign({}, S.buttonOff, { padding: '0 8px' }),
9792
11022
  'data-action': previewing ? 'preview-exit' : 'preview-enter',
9793
11023
  title: previewing
9794
- ? '返回编辑 ' + shortName(openFile)
9795
- : '预览 ' + shortName(openFile) + '(Markdown/HTML 在编辑器区域内渲染,显示当前内容)',
11024
+ ? '返回编辑 ' + fileBaseName(openFile)
11025
+ : '预览 ' + fileBaseName(openFile) + '(Markdown/HTML 在编辑器区域内渲染,显示当前内容)',
9796
11026
  onClick: function () { togglePreview() },
9797
11027
  }, previewing ? '编辑' : '预览'))
9798
11028
  }
@@ -9818,7 +11048,7 @@ var [ui, setUi] = useState(function () {
9818
11048
  onClick: function () { setOpenFile(path) },
9819
11049
  onContextMenu: function (event) { openTabMenu('source', event) },
9820
11050
  },
9821
- shortName(path) + (isDirty(path) ? '*' : ''),
11051
+ fileBaseName(path) + (isDirty(path) ? '*' : ''),
9822
11052
  h('span', {
9823
11053
  style: S.tabClose, title: '关闭', 'data-tab-close': 'source',
9824
11054
  onClick: function (event) { event.stopPropagation(); requestClose(path) },
@@ -9847,7 +11077,7 @@ var [ui, setUi] = useState(function () {
9847
11077
  }, '▾'))
9848
11078
  var prompt = pendingClose !== undefined
9849
11079
  ? h('div', { style: Object.assign({}, S.notice, { display: 'flex', alignItems: 'center', gap: 6 }), 'data-close-prompt': '1' },
9850
- h('span', { style: { flex: '1 1 auto', minWidth: 0 } }, '「' + shortName(pendingClose) + '」有未保存的修改:'),
11080
+ h('span', { style: { flex: '1 1 auto', minWidth: 0 } }, '「' + fileBaseName(pendingClose) + '」有未保存的修改:'),
9851
11081
  h('button', {
9852
11082
  type: 'button', style: S.button, 'data-action': 'save-close', title: '保存后关闭',
9853
11083
  onClick: function () {
@@ -9886,7 +11116,7 @@ var [ui, setUi] = useState(function () {
9886
11116
  ? h('div', { style: Object.assign({}, S.notice, { display: 'flex', alignItems: 'center', gap: 6 }), 'data-bulk-prompt': '1' },
9887
11117
  h('span', { style: { flex: '1 1 auto', minWidth: 0 } },
9888
11118
  pendingBulk.dirty.length + ' 个页签有未保存的修改('
9889
- + pendingBulk.dirty.slice(0, 2).map(shortName).join('、')
11119
+ + pendingBulk.dirty.slice(0, 2).map(fileBaseName).join('、')
9890
11120
  + (pendingBulk.dirty.length > 2 ? ' 等' : '') + '):'),
9891
11121
  h('button', {
9892
11122
  type: 'button', style: S.button, 'data-action': 'bulk-save-close', title: '全部保存后关闭',
@@ -9955,7 +11185,7 @@ var [ui, setUi] = useState(function () {
9955
11185
  h('span', { style: { opacity: 0.7, flex: '0 0 auto' } }, row.open === true ? '●' : '·'),
9956
11186
  h('span', {
9957
11187
  style: { flex: '1 1 auto', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
9958
- }, shortName(row.path) + (dirty ? '*' : '')),
11188
+ }, fileBaseName(row.path) + (dirty ? '*' : '')),
9959
11189
  row.open === true ? null : h('span', { style: { opacity: 0.5, fontSize: 10, flex: '0 0 auto' } }, '历史'))
9960
11190
  return header === null ? item : [header, item]
9961
11191
  }))
@@ -9973,7 +11203,7 @@ var [ui, setUi] = useState(function () {
9973
11203
  return h('div', { style: S.paneOverlay, 'data-editor-diff': openFile },
9974
11204
  h('div', { style: Object.assign({}, S.notice, { display: 'flex', alignItems: 'center', gap: 6 }), 'data-diff-head': '1' },
9975
11205
  h('span', { style: { flex: '1 1 auto', minWidth: 0 } },
9976
- '与磁盘版本对比:' + shortName(openFile) + '(' + changed + ' 行变化;+ 新增 / − 删除)'),
11206
+ '与磁盘版本对比:' + fileBaseName(openFile) + '(' + changed + ' 行变化;+ 新增 / − 删除)'),
9977
11207
  h('button', {
9978
11208
  type: 'button', style: S.button, 'data-action': 'diff-close',
9979
11209
  onClick: function () { setDiffPath(null) },
@@ -10147,11 +11377,25 @@ var [ui, setUi] = useState(function () {
10147
11377
  placeholder: '在工作空间中检索文件…',
10148
11378
  title: '全工作空间文件名检索(结果在搜索框下方,点击直接打开/定位)',
10149
11379
  'data-action': 'tree-search',
10150
- onChange: function (event) { setTreeQuery(event.target.value) },
11380
+ onChange: function (event) {
11381
+ var value = event.target.value
11382
+ setTreeQuery(value)
11383
+ // The dropdown is focus-gated; an edit that lands while the box is
11384
+ // already focused must still bring it back (no focus event fires).
11385
+ if (value.trim() !== '') setSearchFocused(true)
11386
+ },
10151
11387
  onFocus: function () { setSearchFocused(true) },
10152
11388
  onBlur: function () { setSearchFocused(false) },
10153
11389
  onKeyDown: function (event) {
10154
- if (event.key === 'Escape') { event.preventDefault(); setTreeQuery(''); setSearchFocused(false); return }
11390
+ if (event.key === 'Escape') {
11391
+ event.preventDefault()
11392
+ // Escape only gives the caret back: the query and its results stay, so
11393
+ // refocusing the box shows them again. Clearing here used to throw the
11394
+ // typed query away for a key that reads as "leave the box".
11395
+ if (searchInputRef.current !== null) searchInputRef.current.blur()
11396
+ else setSearchFocused(false)
11397
+ return
11398
+ }
10155
11399
  // Whichever dropdown is open is the walkable list: the recent-file list
10156
11400
  // while the box is empty, the results once a query is typed.
10157
11401
  var matches = searchHits !== null && searchHits !== undefined && Array.isArray(searchHits.matches) ? searchHits.matches : []
@@ -10403,6 +11647,9 @@ var [ui, setUi] = useState(function () {
10403
11647
  if (paneConfig !== null && typeof paneConfig.generate === 'function') {
10404
11648
  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' }))
10405
11649
  }
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/端口的规则(与侧边栏控制台共用同一份配置)' }))
10406
11653
  paneActions.push(button('⟲', resetLayout, { key: 'layout-reset', icon: true, height: 20, action: 'layout-reset', title: '还原布局尺寸:左列 300px、调试区 300px、两个下层 260px(不改变最大化状态)' }))
10407
11654
 
10408
11655
  /** Load the visual debug settings from the host (⚙ opens on a fresh read). */
@@ -10516,6 +11763,9 @@ var [ui, setUi] = useState(function () {
10516
11763
  'data-theme': themePreference || 'page',
10517
11764
  onContextMenu: function (event) { event.preventDefault() },
10518
11765
  },
11766
+ proxyOpen === true
11767
+ ? h(ProxyDialog, { scope: { sessionId: sessionId, cwd: cwd }, onClose: function () { setProxyOpen(false) } })
11768
+ : null,
10519
11769
  // The sidebar's CodeMirror theme pins 13px, so the embedded viewer needs
10520
11770
  // this rule, not inheritance, to follow A−/A+.
10521
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),
@@ -11372,12 +12622,20 @@ var [ui, setUi] = useState(function () {
11372
12622
  *
11373
12623
  * Registered in `conversation.session.header.utilities` with order -8, i.e.
11374
12624
  * immediately to the RIGHT of DSH's own "open in app" action (-10) and left of
11375
- * the schedule / log buttons. `sessionId` arrives as a standard slot prop.
11376
- * @param {{sessionId?: string}} props - standard slot props.
12625
+ * the schedule / log buttons. `sessionId` and `useSessions` arrive as standard
12626
+ * slot props.
12627
+ *
12628
+ * The window follows THIS SESSION's workspace, never the remembered one: after
12629
+ * a session switch `knownWorkspaceCwd()` still names the previous session's
12630
+ * workspace (and its single-instance window name), so the button used to bring
12631
+ * back the previous workspace's IDE. The store the slot hands us has the
12632
+ * current session's `cwd`; the fallback only matters on hosts without it.
12633
+ * @param {{sessionId?: string, useSessions?: Function}} props - standard slot props.
11377
12634
  * @returns {object} the button element.
11378
12635
  */
11379
12636
  function RisIdeWindowAction(props) {
11380
12637
  var sessionId = props !== null && props !== undefined && typeof props.sessionId === 'string' ? props.sessionId : ''
12638
+ var sessionCwd = sessionWorkspaceCwd(props !== null && props !== undefined ? props.useSessions : undefined, sessionId)
11381
12639
  var [blocked, setBlocked] = useState(false)
11382
12640
  useEffect(function () {
11383
12641
  if (blocked !== true) return undefined
@@ -11390,7 +12648,7 @@ var [ui, setUi] = useState(function () {
11390
12648
  async function onClick(event) {
11391
12649
  if (event !== undefined && typeof event.preventDefault === 'function') event.preventDefault()
11392
12650
  try {
11393
- var handle = await openStandaloneWindow({ sessionId: sessionId })
12651
+ var handle = await openStandaloneWindow({ sessionId: sessionId, cwd: sessionCwd, windowCwd: sessionCwd })
11394
12652
  if (handle !== null && handle !== undefined && typeof handle.focus === 'function') handle.focus()
11395
12653
  } catch (error) {
11396
12654
  console.warn('dsh-ris-ide: 独立窗口打开失败:' + messageOf(error))
@@ -13081,6 +14339,8 @@ var [ui, setUi] = useState(function () {
13081
14339
  * already delivered: the log viewer re-reads the tail once (see `reloadNonce`).
13082
14340
  */
13083
14341
  var [compactLogNonce, setCompactLogNonce] = useState(0)
14342
+ /** The 「代理」 dialog: address + rule table, shared by both console shapes. */
14343
+ var [compactProxyOpen, setCompactProxyOpen] = useState(false)
13084
14344
  useEffect(function () {
13085
14345
  if (pendingProgram === null) return undefined
13086
14346
  setActive(pendingProgram)
@@ -13091,9 +14351,59 @@ var [ui, setUi] = useState(function () {
13091
14351
  // call sites pass the whole scope object.
13092
14352
  var scope = props ? props.scope : undefined
13093
14353
  var sessionId = scope !== undefined && scope !== null ? scope.sessionId : (props ? props.sessionId : undefined)
14354
+ // The tab body outlives Session switches, so its `sessionId` can name the
14355
+ // Session it was opened in. The sidebar's own marker is the live answer.
14356
+ var rootRef = useRef(null)
14357
+ var [liveSessionId, setLiveSessionId] = useState(function () { return liveSidebarSessionId() })
14358
+ useEffect(function () {
14359
+ function sync() {
14360
+ var live = liveSidebarSessionId(rootRef.current)
14361
+ // A collapsed sidebar renders no visible marker: keep the last good
14362
+ // answer instead of falling back to the stale injected session.
14363
+ if (typeof live !== 'string' || live === '') return
14364
+ setLiveSessionId(function (prev) { return prev === live ? prev : live })
14365
+ }
14366
+ sync()
14367
+ var cleanups = []
14368
+ // A Session switch rewrites the sidebar's markers, so attribute mutations
14369
+ // catch it; `hidden` flips catch the retained wrappers being shown.
14370
+ if (typeof MutationObserver === 'function' && typeof document !== 'undefined') {
14371
+ var observer = new MutationObserver(sync)
14372
+ observer.observe(document.documentElement, { subtree: true, attributes: true, attributeFilter: ['data-sidebar-right-session', 'data-sidebar-right-panel', 'hidden'] })
14373
+ cleanups.push(function () { observer.disconnect() })
14374
+ }
14375
+ // Belt and braces: some switches only repaint, and returning to the window
14376
+ // is the moment a stale panel is most visible.
14377
+ if (typeof setInterval === 'function') {
14378
+ var timer = setInterval(sync, 1500)
14379
+ cleanups.push(function () { clearInterval(timer) })
14380
+ }
14381
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
14382
+ window.addEventListener('focus', sync)
14383
+ cleanups.push(function () { window.removeEventListener('focus', sync) })
14384
+ if (typeof document !== 'undefined') {
14385
+ document.addEventListener('visibilitychange', sync)
14386
+ cleanups.push(function () { document.removeEventListener('visibilitychange', sync) })
14387
+ }
14388
+ }
14389
+ return function () { for (var i = 0; i < cleanups.length; i += 1) cleanups[i]() }
14390
+ }, [])
14391
+ if (typeof liveSessionId === 'string' && liveSessionId !== '') sessionId = liveSessionId
13094
14392
  var cwd = scope !== undefined && scope !== null ? scope.cwd : (props ? props.cwd : undefined)
14393
+ // The tab outlives session switches (`keepMounted`): the remembered workspace
14394
+ // can still name the PREVIOUS session, so the store's value wins when the
14395
+ // slot hands us `useSessions`.
14396
+ var storeCwd = sessionWorkspaceCwd(props ? props.useSessions : undefined, sessionId)
14397
+ if (typeof storeCwd === 'string' && storeCwd !== '') cwd = storeCwd
13095
14398
  // A stale session id must not blank the panel: the host still accepts a cwd.
13096
14399
  if (typeof cwd !== 'string' || cwd === '') cwd = knownWorkspaceCwd()
14400
+ // Selections and the followed log belong to the workspace they were made in,
14401
+ // so a Session switch drops them instead of showing another project's log.
14402
+ var sessionIdentity = typeof sessionId === 'string' ? sessionId : ''
14403
+ useEffect(function () {
14404
+ setCompactPick(undefined)
14405
+ setActive(undefined)
14406
+ }, [sessionIdentity])
13097
14407
  // COMPACT mode is the sidebar panel: console rows on top, ONE program's
13098
14408
  // live log below. The full IDE (tree/editor/debug) lives only in the
13099
14409
  // standalone window, so the sidebar stays cheap and readable.
@@ -13390,7 +14700,7 @@ var [ui, setUi] = useState(function () {
13390
14700
  if (sidebar !== undefined && sidebar !== null && typeof sidebar.openResource === 'function') {
13391
14701
  try {
13392
14702
  sidebar.openResource(officialPreviewAddress({ sessionId: sessionId, cwd: cwd }, path))
13393
- setState(function (prev) { return Object.assign({}, prev, { note: '已在右侧栏打开 ' + shortName(path) + '(改完保存即生效)' }) })
14703
+ setState(function (prev) { return Object.assign({}, prev, { note: '已在右侧栏打开 ' + fileBaseName(path) + '(改完保存即生效)' }) })
13394
14704
  } catch (error) {
13395
14705
  setState(function (prev) { return Object.assign({}, prev, { note: '打开配置失败:' + messageOf(error) }) })
13396
14706
  }
@@ -13682,8 +14992,11 @@ var [ui, setUi] = useState(function () {
13682
14992
  onClick: function () { toggleCompactMax(section) },
13683
14993
  }, isMaxed ? '⤡' : '⤢')
13684
14994
  }
13685
- return h('div', { style: S.root, 'data-panel': 'compact' },
14995
+ return h('div', { ref: rootRef, style: S.root, 'data-panel': 'compact' },
13686
14996
  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,
13687
15000
  h('div', { style: S.bar, 'data-compact-bar': '1' },
13688
15001
  h('span', { style: S.status }, state.loading ? '扫描中…' : (state.programs.length + ' 个项目')),
13689
15002
  h('span', { style: S.meta, title: state.root }, state.root || ''),
@@ -13691,6 +15004,11 @@ var [ui, setUi] = useState(function () {
13691
15004
  // The config actions live on the CONSOLE title bar in both shapes: the
13692
15005
  // sidebar's title bar is this top bar, so it gets the same two icons
13693
15006
  // 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
+ }, '🌐'),
13694
15012
  configExists === true
13695
15013
  ? h('button', {
13696
15014
  type: 'button', style: S.paneIcon, 'data-action': 'compact-config-open',
@@ -14025,6 +15343,8 @@ var [ui, setUi] = useState(function () {
14025
15343
  // The standalone window: the header button, the popup helper and the
14026
15344
  // mount entry the window's own page calls (none of them needs DSH's ctx).
14027
15345
  RisIdeWindowAction: RisIdeWindowAction,
15346
+ /** The header button's cwd source: the session store, never the remembered one. */
15347
+ sessionWorkspaceCwd: sessionWorkspaceCwd,
14028
15348
  openStandaloneWindow: openStandaloneWindow,
14029
15349
  mountStandalone: mountStandalone,
14030
15350
  StandaloneWindow: StandaloneWindow,
@@ -14040,6 +15360,8 @@ var [ui, setUi] = useState(function () {
14040
15360
  drainOpenRequests: drainOpenRequests,
14041
15361
  ProgramWorkbench: ProgramWorkbench,
14042
15362
  ProgramsPanel: ProgramsPanel,
15363
+ // Proxy dialog (address + rule table), rendered from both console shapes.
15364
+ ProxyDialog: ProxyDialog,
14043
15365
  IdeErrorBoundary: IdeErrorBoundary,
14044
15366
  PROGRAM_TAB_ID: PROGRAM_TAB_ID,
14045
15367
  // The compact sidebar shape: its default log-pane height (240px) and the