diff --git a/README.en.md b/README.en.md index 3cd49ef..7f7089f 100644 --- a/README.en.md +++ b/README.en.md @@ -28,7 +28,7 @@ After installation or an upgrade, restart DSH Web and refresh the page. Check au ## Start in 3 steps -1. **Configure a host**: open Settings → Remote workspaces to edit SSH configuration or save credentials. Connectivity checks run automatically; no manual connection step is required. +1. **Configure a host**: open Settings → Remote workspaces to edit SSH configuration or save credentials. Hosts already in `~/.ssh/config` are listed there — open the row's `…` menu and choose **Edit** to save it as a machine and fill in its login password (the entry is the same `…` menu before and after saving). Connectivity checks run automatically; no manual connection step is required. 2. **Create a workspace**: Add workspace → Remote, then choose a host and folder. Each workspace binds its own host; settings have no folder selection or global active host. 3. **Develop remotely**: open workspace files or enter IDE mode to edit with syntax highlighting, search, run commands and collaborate with the agent. Files open ready to edit. @@ -62,7 +62,7 @@ The terminal starts in the session's remote directory. A pixel fish welcomes you ### Port forwarding (SSH tunnels) -Open the listener on the side that initiates the connection: a listener here is a local forward (`ssh -L`); one on the remote is a reverse forward (`ssh -R`). Run several at once, and tick auto reconnect per row to restore only the forwards that were running, scoped to their machine. Enabling it for a reverse forward first warns that the remote will listen again. +Open the listener on the side that initiates the connection: a listener here is a local forward (`ssh -L`); one on the remote is a reverse forward (`ssh -R`). Run several at once. Each forward names its **host**, so you can define a tunnel for a machine that is not connected yet and start it once that machine is. Every forward can be edited in place — direction, ports, target or owning host; a running one is stopped first and restarted with the new settings. Tick auto reconnect per row to restore only the forwards that were running, scoped to their machine — enabling it for a reverse forward first warns that the remote will listen again. Upgrading from an older version: auto-reconnect entries that predate `lastActive` are paused and marked "Re-confirm" in the row; tick them again to opt back in (reverse forwards also need the remote-listening warning acknowledged). diff --git a/README.md b/README.md index 027e90b..7336ad7 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ dsh plugin --profile web add dsh-remote ## 3 步开始 -1. **配置主机**:设置 → 远程工作区,编辑 SSH 配置或保存主机凭据;打开设置会自动检查连通性,无需手动“连接”。 +1. **配置主机**:设置 → 远程工作区,编辑 SSH 配置或保存主机凭据;直接写在 `~/.ssh/config` 里的 Host 会出现在主机列表中,点该行的「…」菜单 →「编辑」即可保存成机器并填写登录密码(保存前后入口都是同一个「…」菜单)。打开设置会自动检查连通性,无需手动“连接”。 2. **创建工作区**:添加工作区 → 远程,选择主机与目录。每个工作区独立绑定主机,设置页不选目录或“当前远程机”。 3. **开始开发**:打开工作区文件或切换 IDE 模式,文件打开即可编辑并显示语法高亮,在远端搜索、运行命令并与 Agent 协作。 @@ -62,7 +62,7 @@ dsh plugin --profile web add dsh-remote ### 端口转发(SSH 隧道) -谁要发起访问,就在谁那边开监听口:监听口开在本机是本地转发(`ssh -L`),开在远端是远程转发(`ssh -R`)。可同时运行多条;每行能直接勾选「自动重连」——只恢复上次运行中的转发,且按机器隔离,反向转发首次勾选会提示远端监听风险。 +谁要发起访问,就在谁那边开监听口:监听口开在本机是本地转发(`ssh -L`),开在远端是远程转发(`ssh -R`)。可同时运行多条;添加转发时可以选择「主机」,每条转发只属于一台机器——给还没连接的主机也能先存下转发,连上后再启动。每条转发都可以点「编辑」调整方向、端口、目标或所属主机,运行中的会先停止、保存后按新配置重新启动。每行能直接勾选「自动重连」——只恢复上次运行中的转发,且按机器隔离,反向转发首次勾选会提示远端监听风险。 从旧版本升级:旧版没有 `lastActive` 的「自动重连」配置会暂停,行上显示「需重新确认」;重新勾选后才会参与自动恢复(反向转发需重新确认远端监听)。 diff --git a/lib/client.js b/lib/client.js index 0cf5429..c404dc1 100644 --- a/lib/client.js +++ b/lib/client.js @@ -393,6 +393,8 @@ window.__ModuleLoader__.load({ 'settings.edit': '编辑', 'settings.delete': '删除', 'settings.editMachine': '编辑机器', + 'settings.addMachine': '新增机器', + 'settings.adoptAliasHint': '把 {alias} 保存为机器,可在这里填写登录密码(保存后即可继续编辑)', 'settings.badgeSshConfig': 'ssh cfg', // Issue #51 — transport backend (GSSAPI/Kerberos via system OpenSSH). 'settings.badgeOpenssh': 'openssh', @@ -443,6 +445,7 @@ window.__ModuleLoader__.load({ // 灰按钮必须能解释自己:用户「点了没反应」时唯一能拿到的线索就是 hover 提示。 'settings.saveNeedsHost': '先填写主机地址才能保存', 'settings.saveHint': '保存这台机器(留空的密码/私钥/passphrase 沿用已保存的值)', + 'settings.poolRepointFailed': '机器已保存,但切换当前连接失败:{msg}。请重新选择这台机器,或重启 DSH。', 'settings.fwdNeedsPort': '先填写监听端口才能添加转发', 'settings.fwdAddHint': '添加一条端口转发', 'settings.advCollapse': '收起高级配置', @@ -493,6 +496,20 @@ window.__ModuleLoader__.load({ 'settings.fwdAutoNoticeCancel': '取消', 'settings.fwdAutoNoticeDontShow': '不再提示', 'settings.fwdAdd': '添加转发', + 'settings.fwdHost': '主机', + 'settings.fwdHostHint': '这条转发属于哪台主机;只有连上该主机时才能启动。可以给还没连接的主机先存下转发。', + 'settings.fwdHostCurrent': '当前', + 'settings.fwdHostEmpty': '(暂无主机)', + 'settings.fwdHostNeeds': '先选择一台主机才能添加转发', + 'settings.fwdAddedOther': '已添加:连上 {name} 后即可启动这条转发', + 'settings.fwdHostStale': '当前运行的插件宿主端还是旧版本,不认识“主机”字段;已撤销这条转发。请重启 DSH 后再添加。', + 'settings.fwdEdit': '编辑', + 'settings.fwdEditHint': '修改方向、监听端口、目标或所属主机;运行中的转发会先停止,保存后按新配置重新启动', + 'settings.fwdSaveChanges': '保存修改', + 'settings.fwdCancelEdit': '取消', + 'settings.fwdUpdated': '已保存修改', + 'settings.fwdEditingBadge': '编辑中', + 'settings.fwdUpdateStale': '当前运行的插件宿主端还是旧版本,没能保存这些修改;已恢复原来的转发。请重启 DSH 后再编辑。', 'settings.cleanup': '工作区清理(本地镜像与对话)', 'settings.cleanupRefresh': '刷新', 'settings.cleanupEmpty': '没有本地镜像。选定一个远程工作区后它会出现在这里。', @@ -1000,6 +1017,8 @@ window.__ModuleLoader__.load({ 'settings.edit': 'Edit', 'settings.delete': 'Delete', 'settings.editMachine': 'Edit machine', + 'settings.addMachine': 'New machine', + 'settings.adoptAliasHint': 'Save {alias} as a machine so you can set its login password here (it stays editable afterwards)', 'settings.badgeSshConfig': 'ssh cfg', // Issue #51 — transport backend (GSSAPI/Kerberos via system OpenSSH). 'settings.badgeOpenssh': 'openssh', @@ -1044,6 +1063,7 @@ window.__ModuleLoader__.load({ 'settings.testNeedsHost': 'Fill in the host before testing', 'settings.saveNeedsHost': 'Fill in the host before saving', 'settings.saveHint': 'Save this machine (a blank password/key/passphrase keeps the saved one)', + 'settings.poolRepointFailed': 'The machine was saved, but re-pointing the active connection failed: {msg}. Select the machine again or restart DSH.', 'settings.fwdNeedsPort': 'Fill in the listen port before adding a forward', 'settings.fwdAddHint': 'Add a port forward', 'settings.advCollapse': 'Hide advanced options', @@ -1094,6 +1114,20 @@ window.__ModuleLoader__.load({ 'settings.fwdAutoNoticeCancel': 'Cancel', 'settings.fwdAutoNoticeDontShow': "Don't show again", 'settings.fwdAdd': 'Add forward', + 'settings.fwdHost': 'Host', + 'settings.fwdHostHint': 'Which host this tunnel belongs to. It can start only while that host is connected; you can still define it for a host that is not connected yet.', + 'settings.fwdHostCurrent': 'current', + 'settings.fwdHostEmpty': '(no hosts yet)', + 'settings.fwdHostNeeds': 'Pick a host before adding a forward', + 'settings.fwdAddedOther': 'Added — start it once {name} is connected', + 'settings.fwdHostStale': 'The running host half predates the host field and would have attached this tunnel to the connected machine. The forward was removed — restart DSH and add it again.', + 'settings.fwdEdit': 'Edit', + 'settings.fwdEditHint': 'Change the direction, listen port, target or host; a running forward is stopped first and then restarted with the new settings', + 'settings.fwdSaveChanges': 'Save changes', + 'settings.fwdCancelEdit': 'Cancel', + 'settings.fwdUpdated': 'Changes saved', + 'settings.fwdEditingBadge': 'Editing', + 'settings.fwdUpdateStale': 'The running host half predates forward editing and could not store these changes; the previous forward was restored. Restart DSH and edit again.', 'settings.cleanup': 'Workspace cleanup (local mirrors & chats)', 'settings.cleanupRefresh': 'Refresh', 'settings.cleanupEmpty': 'No local mirrors yet. Pick a remote workspace and it shows up here.', @@ -1949,7 +1983,14 @@ window.__ModuleLoader__.load({ const formBaseline = React.useRef(settingsEditorDraft?.baseline || null) const probeRevision = React.useRef(0) const [machines, setMachines] = React.useState([]) + // Which machine the pool is on: the forwards form defaults its host select + // to it, marks it as 当前, and uses it to tell the user when a newly added + // forward belongs to a different host. + const [currentId, setCurrentId] = React.useState('') const [hostsLoaded, setHostsLoaded] = React.useState(false) + // The machine editor also serves NEW records (adopting a ~/.ssh/config + // host or a manual machine), so it cannot be keyed on `form.id`. + const [formOpen, setFormOpen] = React.useState(() => !!settingsEditorDraft) const [form, setForm] = React.useState(() => settingsEditorDraft?.form || { name: '', host: '', port: '22', username: 'root', password: '', privateKeyPath: '', passphrase: '', workspace: '', hostKeyMode: '', useAgent: false, keyboardInteractive: false, @@ -1963,8 +2004,8 @@ window.__ModuleLoader__.load({ // between "the plugin remembered my password" and "the plugin lost it". passwordSet: false, passphraseSet: false, proxyPasswordSet: false, }) - React.useEffect(() => { if (form.id) document.getElementById(settingsId + '-field-n')?.focus?.() }, [form.id]) - const formDirty = !!form.id && formBaseline.current !== null && JSON.stringify(form) !== formBaseline.current + React.useEffect(() => { if (formOpen) document.getElementById(settingsId + '-field-n')?.focus?.() }, [formOpen]) + const formDirty = formOpen && formBaseline.current !== null && JSON.stringify(form) !== formBaseline.current React.useEffect(() => { settingsEditorDraft = formDirty ? { form, baseline: formBaseline.current } : null }, [form, formDirty]) @@ -1973,7 +2014,9 @@ window.__ModuleLoader__.load({ const [err, setErr] = React.useState('') const [tst, setTst] = React.useState('') // idle | testing | ok | failing const [forwards, setForwards] = React.useState([]) - const [fwdForm, setFwdForm] = React.useState({ listenPort: '', targetHost: '127.0.0.1', targetPort: '', direction: 'local', autoStart: false }) + const [fwdForm, setFwdForm] = React.useState({ listenPort: '', targetHost: '127.0.0.1', targetPort: '', direction: 'local', autoStart: false, machineId: '' }) + // Which saved definition the form is editing ('' = the form adds a new one). + const [fwdEditId, setFwdEditId] = React.useState('') const [auditLines, setAuditLines] = React.useState([]) // The audit LOG FILE on the host machine: its path plus the outcome of the last // 打开/显示 attempt. The browser cannot open a file that lives on the host, so @@ -2138,7 +2181,7 @@ window.__ModuleLoader__.load({ } const refresh = () => api('GET', '/dsh-remote/machines').then((r) => { - setMachines(r.machines || []); setHostsLoaded(true) + setMachines(r.machines || []); setCurrentId(String((r && r.currentId) || '')); setHostsLoaded(true) }) React.useEffect(() => { refresh().catch(error => setErr(String(error.message || error))) }, []) @@ -2158,6 +2201,15 @@ window.__ModuleLoader__.load({ } }, []) + React.useEffect(() => { + setFwdForm((prev) => { + if (!machines.length) return prev.machineId ? { ...prev, machineId: '' } : prev + if (prev.machineId && machines.some((m) => m.id === prev.machineId)) return prev + const next = machines.some((m) => m.id === currentId) ? currentId : machines[0].id + return next === prev.machineId ? prev : { ...prev, machineId: next } + }) + }, [machines, currentId]) + // ── update state ──────────────────────────────────────────────────────── const [upd, setUpd] = React.useState(null) // { current, latest, updateAvailable, updateMode, updatedMarker } const [updBusy, setUpdBusy] = React.useState(false) @@ -2304,6 +2356,7 @@ window.__ModuleLoader__.load({ } formBaseline.current = JSON.stringify(next) setForm(next) + setFormOpen(true) // 编辑时若该机器用了高级配置(私钥/agent/跳板/钥匙串/系统 OpenSSH 后端),自动展开折叠区 setAdvOpen(!!(m.privateKeyPath || m.useAgent || m.keyboardInteractive || (m.proxy && m.proxy.host) || m.backend === 'openssh' || m.webAttachCommand || m.webAttachDiscoverCommand || (m.credentialBackend && m.credentialBackend !== 'plain'))) } @@ -2320,7 +2373,10 @@ window.__ModuleLoader__.load({ setProbeGeneration(value => value + 1) window.setTimeout(() => document.getElementById(focusId)?.focus?.(), 0) } - const clearForm = () => setForm({ name: '', host: '', port: '22', username: 'root', password: '', privateKeyPath: '', passphrase: '', workspace: '', hostKeyMode: '', useAgent: false, keyboardInteractive: false, encryptPassword: false, proxyHost: '', proxyPort: '22', proxyUser: '', proxyPassword: '', proxyKey: '', backend: 'native', sshBinary: '', webAttachCommand: '', webAttachDiscoverCommand: '', id: '', useSshConfig: false, passwordSet: false, passphraseSet: false, proxyPasswordSet: false }) + const clearForm = () => { + setFormOpen(false) + setForm({ name: '', host: '', port: '22', username: 'root', password: '', privateKeyPath: '', passphrase: '', workspace: '', hostKeyMode: '', useAgent: false, keyboardInteractive: false, encryptPassword: false, proxyHost: '', proxyPort: '22', proxyUser: '', proxyPassword: '', proxyKey: '', backend: 'native', sshBinary: '', webAttachCommand: '', webAttachDiscoverCommand: '', id: '', useSshConfig: false, passwordSet: false, passphraseSet: false, proxyPasswordSet: false }) + } const save = (action) => { if (busy) return probeRevision.current++ @@ -2380,6 +2436,9 @@ window.__ModuleLoader__.load({ // say so, or the user cannot tell their workspaces came along. else if (r && r.reboundMirrors) setMsg(tr('settings.saved') + ' — ' + tr('settings.rebound', { n: r.reboundMirrors })) else setMsg(form.id ? tr('settings.saved') : tr('settings.added')) + // The record is saved, but the LIVE pool could not be re-pointed at + // the new address — say so, or the next 启动 still dials the old host. + if (r && r.poolWarning) setErr(tr('settings.poolRepointFailed', { msg: r.poolWarning })) setProbeGeneration(value => value + 1) }).catch((e) => setErr(String((e && e.message) || e))).finally(() => setBusy(false)) } @@ -2398,6 +2457,33 @@ window.__ModuleLoader__.load({ const uniqueMachines = machines const discovered = dedupeDiscoveredForSaved(sshHosts || [], machines) + // A discovered ~/.ssh/config entry is not a registry record yet; the menu + // edits it through the SAME machine form, prefilled as an alias. + const discoveredMachine = (h) => { + const alias = String(h.alias || h.host) + return { + name: alias, host: alias, port: Number(h.port) || 22, username: h.user || '', + useSshConfig: true, backend: 'openssh', + } + } + + // Open the shared host menu ATTACHED to the `...` button that was pressed. + // + // DSH 0.2.2-alpha.2 replaced `getAnchorRect` with CSS anchors + // (`anchorRef` / `anchorPoint`). An older host ignores the new props, a + // newer host ignores the old one, so pass BOTH: before the refactor the + // rect was the only way to anchor a body-portaled menu to a host-owned + // trigger, and after it the ref is. Passing only the rect (the old code) + // left the menu unattached on a current host. + const openHostMenu = (event, key, machine, discovered) => { + const el = event.currentTarget + setSettingsMenu({ + key, machine, discovered: !!discovered, el, + anchorRef: { current: el }, + getAnchorRect: () => el.getBoundingClientRect(), + }) + } + // Keep row order stable while connectivity results arrive. const sortedMachines = [...uniqueMachines].sort((a, b) => String(a.name || a.host).localeCompare(String(b.name || b.host))) // Every saved machine id gets its own probe (credentials and backend are @@ -2509,12 +2595,100 @@ window.__ModuleLoader__.load({ applyFwdAutoStart(fwdNotice.target, true) setFwdNotice(null) } + const resetFwdForm = () => setFwdForm((form) => ({ listenPort: '', targetHost: '127.0.0.1', targetPort: '', direction: 'local', autoStart: false, machineId: form.machineId })) + const fwdFields = () => ({ + direction: fwdForm.direction, + listenPort: Number(fwdForm.listenPort), + targetHost: fwdForm.targetHost || '127.0.0.1', + targetPort: Number(fwdForm.targetPort) || Number(fwdForm.listenPort), + autoStart: !!fwdForm.autoStart, + machineId: fwdForm.machineId, + }) + const beginFwdEdit = (f) => { + setFwdEditId(f.id); setErr(''); setMsg('') + setFwdForm({ + listenPort: String(f.listenPort ?? ''), targetHost: String(f.targetHost || '127.0.0.1'), + targetPort: String(f.targetPort ?? ''), direction: f.direction === 'reverse' ? 'reverse' : 'local', + autoStart: !!f.autoStart, machineId: f.machineId || '', + }) + setFwdOpen(true) + // With several forwards the form sits below all rows; bring it into view + // so the click visibly lands somewhere. + window.setTimeout(() => { + document.getElementById(settingsId + '-fwd-form')?.scrollIntoView?.({ block: 'nearest', behavior: 'smooth' }) + }, 0) + } + const cancelFwdEdit = () => { setFwdEditId(''); setErr(''); resetFwdForm() } const fwdDefine = () => { if (!fwdForm.listenPort) return - api('POST', '/dsh-remote/forwards', { action: 'define', listenPort: Number(fwdForm.listenPort), targetHost: fwdForm.targetHost || '127.0.0.1', targetPort: Number(fwdForm.targetPort) || Number(fwdForm.listenPort), direction: fwdForm.direction, autoStart: fwdForm.autoStart }) - .then((r) => { setForwards(r.forwards || []); setFwdForm({ listenPort: '', targetHost: '127.0.0.1', targetPort: '', direction: 'local', autoStart: false }) }) + if (!fwdForm.machineId) { setErr(tr('settings.fwdHostNeeds')); return } + const machineId = fwdForm.machineId + api('POST', '/dsh-remote/forwards', { action: 'define', ...fwdFields() }) + .then((r) => { + const added = r && r.forward + // A running HOST half that predates this field ignores `machineId` and + // tags the ACTIVE machine instead — the tunnel would silently belong to + // the wrong host. Detect it, undo the definition and say what to do. + if (added && added.machineId !== machineId) { + api('POST', '/dsh-remote/forwards', { action: 'remove', id: added.id }).then(refreshForwards).catch(() => {}) + setErr(tr('settings.fwdHostStale')) + return + } + setForwards(r.forwards || []) + resetFwdForm() + // Defining for a host that is not connected is legitimate (it becomes + // startable once that host is), but the row gives no other clue — say + // which host the tunnel now belongs to. + if (added && added.machineId && added.machineId !== currentId) { + const target = machines.find((m) => m.id === added.machineId) + setMsg(tr('settings.fwdAddedOther', { name: (target && (target.name || target.host)) || added.machineId })) + } + }) .catch((e) => setErr(String((e && e.message) || e))) } + // Editing an EXISTING definition, including one that is running. A live + // tunnel keeps its old bind until it is torn down, so the client stops it, + // patches the record and starts it again — "adjust it and keep it running" + // is what the button promises. + const fwdSaveEdit = async () => { + const id = fwdEditId + const target = forwards.find((f) => f.id === id) + if (!id || !target) { setFwdEditId(''); resetFwdForm(); return } + if (!fwdForm.listenPort) return + if (!fwdForm.machineId) { setErr(tr('settings.fwdHostNeeds')); return } + const wasActive = !!target.active + setFwdBusy((m) => ({ ...m, [id]: true })); setErr(''); setMsg('') + const fields = fwdFields() + try { + if (wasActive) await api('POST', '/dsh-remote/forwards', { action: 'stop', id }) + const r = await api('POST', '/dsh-remote/forwards', { action: 'update', id, ...fields }) + const saved = r && r.forward + // An older HOST half only knows `autoStart` and ignores the bind + // fields — it would answer "ok" while nothing changed. Compare what it + // stored with what was asked, put the tunnel back and say so. + const applied = saved && saved.direction === fields.direction + && saved.listenPort === fields.listenPort && saved.targetHost === fields.targetHost + && saved.targetPort === fields.targetPort + && (saved.machineId || null) === (fields.machineId || null) + if (saved && !applied) { + setErr(tr('settings.fwdUpdateStale')) + refreshForwards() + if (wasActive) api('POST', '/dsh-remote/forwards', { action: 'start', id }).catch(() => {}) + return + } + if (Array.isArray(r.forwards)) setForwards(r.forwards) + setFwdEditId(''); resetFwdForm(); setMsg(tr('settings.fwdUpdated')) + if (wasActive) { + const s = await api('POST', '/dsh-remote/forwards', { action: 'start', id }) + if (Array.isArray(s.forwards)) setForwards(s.forwards) + } + } catch (e) { + setErr(String((e && e.message) || e)) + refreshForwards() + } finally { + setFwdBusy((m) => { const next = { ...m }; delete next[id]; return next }) + } + } const fieldNote = text => React.createElement('div', { className: 'dsh-rw-settings-field-note', style: { color: T.muted } }, text) const row = (label, ctrl, k) => { @@ -2582,7 +2756,7 @@ window.__ModuleLoader__.load({ msg ? React.createElement('div', { role: 'status', 'aria-live': 'polite', className: 'dsh-rw-settings-message', style: { color: T.muted, fontSize: 12, lineHeight: 1.5 } }, msg) : null, err ? React.createElement('div', { role: 'alert', className: 'dsh-rw-settings-message', style: { color: T.danger, fontSize: 13, lineHeight: 1.5 } }, err) : null, React.createElement('div', { id: settingsId + '-hosts', role: 'tabpanel', 'aria-labelledby': settingsId + '-tab-hosts', hidden: settingsTab !== 'hosts', className: 'dsh-rw-settings-panel', style: { display: settingsTab === 'hosts' ? 'flex' : 'none' } }, - React.createElement('div', { className: 'dsh-rw-settings-card dsh-rw-settings-hosts', hidden: !!form.id || !!sshEditor, style: { ...boxS, display: form.id || sshEditor ? 'none' : undefined } }, + React.createElement('div', { className: 'dsh-rw-settings-card dsh-rw-settings-hosts', hidden: formOpen || !!sshEditor, style: { ...boxS, display: formOpen || sshEditor ? 'none' : undefined } }, React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, flexWrap: 'wrap' } }, React.createElement('div', { style: { fontSize: 13, fontWeight: 600 } }, tr('settings.pickHost')), React.createElement('span', { style: { fontSize: 11, opacity: 0.6 } }, tr('settings.hostListSource')), @@ -2619,7 +2793,24 @@ window.__ModuleLoader__.load({ React.createElement('div', { style: { flex: 1, fontSize: 13, minWidth: 180 } }, React.createElement('div', { className: 'dsh-rw-settings-identity' }, React.createElement('span', { style: { fontWeight: 600 } }, alias), React.createElement('code', { style: { fontSize: 12, opacity: 0.75 } }, target), React.createElement('div', { className: 'dsh-rw-settings-host-flags' }, h.proxyJump ? pill('', tr('settings.badgeProxy')) : null, h.identityFile ? pill('', tr('settings.badgeKey')) : null)), rowResult(key)), - React.createElement('div', { className: 'dsh-rw-settings-host-actions' }, hostProbe(key), React.createElement('span', { className: 'dsh-rw-settings-menu-spacer', 'aria-hidden': true }))) + React.createElement('div', { className: 'dsh-rw-settings-host-actions' }, + hostProbe(key), + // Same `...` entry as a saved machine, so the row does not + // change shape the moment it is adopted. The menu only holds + // 编辑 (there is no registry record to delete — the alias + // lives in ~/.ssh/config). + HostMenu ? React.createElement('button', { + type: 'button', className: 'dsh-rw-action', + title: tr('settings.adoptAliasHint', { alias }), 'aria-label': tr('settings.adoptAliasHint', { alias }), + id: settingsId + '-actions-ssh-' + alias, 'aria-haspopup': 'menu', + 'aria-expanded': settingsMenu?.key === key, + onClick: event => openHostMenu(event, key, discoveredMachine(h), true), + }, React.createElement(WorkbenchIcon, { name: 'more' })) + : React.createElement('details', { className: 'dsh-rw-settings-menu' }, + React.createElement('summary', { 'aria-label': tr('settings.adoptAliasHint', { alias }) }, React.createElement(WorkbenchIcon, { name: 'more', size: 16 })), + React.createElement('div', { className: 'dsh-rw-settings-menu-items', style: { background: T.bg, borderColor: T.border } }, + React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: buttonS, onClick: () => startEdit(discoveredMachine(h)) }, tr('settings.edit')))), + React.createElement('span', { className: 'dsh-rw-settings-menu-spacer', 'aria-hidden': true }))) }) : (sshError ? React.createElement('div', { style: { fontSize: 11, color: T.danger, lineHeight: 1.6, marginBottom: 6, wordBreak: 'break-all' } }, @@ -2642,7 +2833,7 @@ window.__ModuleLoader__.load({ rowResult('machine:' + m.id)), React.createElement('div', { className: 'dsh-rw-settings-host-actions' }, hostProbe('machine:' + m.id), - HostMenu ? React.createElement('button', { type: 'button', className: 'dsh-rw-action', title: tr('settings.hostActions', { name: m.name || m.host }), 'aria-label': tr('settings.hostActions', { name: m.name || m.host }), id: settingsId + '-actions-' + m.id, 'aria-haspopup': 'menu', 'aria-expanded': settingsMenu?.machine.id === m.id, onClick: event => setSettingsMenu({ machine: m, anchor: event.currentTarget.getBoundingClientRect() }) }, HostEllipsisIcon ? React.createElement(HostEllipsisIcon, { size: 16 }) : React.createElement(WorkbenchIcon, { name: 'more' })) + HostMenu ? React.createElement('button', { type: 'button', className: 'dsh-rw-action', title: tr('settings.hostActions', { name: m.name || m.host }), 'aria-label': tr('settings.hostActions', { name: m.name || m.host }), id: settingsId + '-actions-' + m.id, 'aria-haspopup': 'menu', 'aria-expanded': settingsMenu?.key === 'machine:' + m.id, onClick: event => openHostMenu(event, 'machine:' + m.id, m, false) }, HostEllipsisIcon ? React.createElement(HostEllipsisIcon, { size: 16 }) : React.createElement(WorkbenchIcon, { name: 'more' })) : React.createElement('details', { className: 'dsh-rw-settings-menu' }, React.createElement('summary', { 'aria-label': tr('settings.hostActions', { name: m.name || m.host }) }, React.createElement(WorkbenchIcon, { name: 'more', size: 16 })), React.createElement('div', { className: 'dsh-rw-settings-menu-items', style: { background: T.bg, borderColor: T.border } }, @@ -2660,10 +2851,10 @@ window.__ModuleLoader__.load({ React.createElement('label', { htmlFor: settingsId + '-ssh-text', style: { fontSize: 12, color: T.muted } }, tr('settings.sshConfigEditorHint')), React.createElement('textarea', { id: settingsId + '-ssh-text', 'aria-label': tr('settings.sshConfigEditorTitle'), spellCheck: false, autoCapitalize: 'off', readOnly: sshEditorBusy, value: sshEditor.text, onChange: event => setSshEditor({ ...sshEditor, text: event.target.value }), onKeyDown: event => { if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') { event.preventDefault(); saveSshConfig() } }, style: { ...inputS, width: '100%', boxSizing: 'border-box', minHeight: 320, resize: 'vertical', fontFamily: 'ui-monospace, SFMono-Regular, Consolas, monospace', fontSize: 12, lineHeight: 1.7, whiteSpace: 'pre', tabSize: 2, marginTop: 8 } }), React.createElement('div', { role: 'status', style: { fontSize: 11, color: T.muted, marginTop: 6 } }, sshEditorDirty ? tr('settings.unsaved') : tr('settings.sshConfigClean'))) : null, - form.id ? React.createElement('div', { className: 'dsh-rw-settings-card dsh-rw-settings-editor', style: boxS }, + formOpen ? React.createElement('div', { className: 'dsh-rw-settings-card dsh-rw-settings-editor', style: boxS }, React.createElement('div', { className: 'dsh-rw-settings-editor-heading' }, React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: buttonS, onClick: closeEditor, disabled: busy, 'aria-label': tr('settings.backHosts') }, React.createElement(Chevron, { dir: 'left', size: 14 }), tr('settings.backHosts')), - React.createElement('div', { style: { minWidth: 0, flex: 1 } }, React.createElement('strong', {}, form.name || form.host), React.createElement('div', { style: { color: formDirty ? T.warn : T.muted, fontSize: 11 } }, formDirty ? tr('settings.unsaved') : tr('settings.editMachine')))), + React.createElement('div', { style: { minWidth: 0, flex: 1 } }, React.createElement('strong', {}, form.name || form.host), React.createElement('div', { style: { color: formDirty ? T.warn : T.muted, fontSize: 11 } }, formDirty ? tr('settings.unsaved') : (form.id ? tr('settings.editMachine') : tr('settings.addMachine'))))), React.createElement('div', { className: 'dsh-rw-settings-editor-actions', style: { background: T.bg, borderColor: T.border } }, React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: buttonS, onClick: closeEditor, disabled: busy }, tr('settings.cancelEdit')), React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: buttonS, onClick: testConn, disabled: busy || !form.host.trim() || tst === 'testing', title: form.host.trim() ? tr('settings.testHint') : tr('settings.testNeedsHost') }, tst === 'testing' ? tr('settings.testing') : tst === 'ok' ? tr('settings.testOk') : tr('settings.testConn')), @@ -2828,12 +3019,25 @@ window.__ModuleLoader__.load({ React.createElement('div', { style: { opacity: 0.65, fontSize: 11, lineHeight: 1.5, marginBottom: 8 } }, tr('settings.forwardsHint')), forwards.length ? forwards.map((f) => { const busy = !!fwdBusy[f.id] - return React.createElement('div', { key: f.id, className: 'dsh-rw-row', style: { display: 'flex', gap: 8, alignItems: 'center', padding: '6px 0', fontSize: 12, fontFamily: 'monospace' } }, + const editing = fwdEditId === f.id + return React.createElement('div', { + key: f.id, className: 'dsh-rw-row', 'data-fwd-editing': editing ? 'true' : undefined, + 'aria-current': editing ? 'true' : undefined, + style: { + display: 'flex', gap: 8, rowGap: 4, alignItems: 'center', flexWrap: 'wrap', padding: '6px 8px', margin: '0 -8px', fontSize: 12, fontFamily: 'monospace', + // The row the form below is editing must stay identifiable while + // the user is typing in fields that hide the original values. + borderRadius: 6, transition: 'background .12s ease, box-shadow .12s ease', + background: editing ? T.bg2 : undefined, + boxShadow: editing ? 'inset 3px 0 0 ' + T.primary : undefined, + }, + }, React.createElement('span', { style: { color: f.active ? T.ok : T.muted } }, f.active ? '●' : '○'), React.createElement('span', { title: f.direction === 'reverse' ? tr('settings.fwdDirReverse') : tr('settings.fwdDirLocal'), style: { flex: '0 0 auto', color: T.muted, opacity: 0.85 }, }, f.direction === 'reverse' ? '-R' : '-L'), + editing ? React.createElement('span', { style: { flex: '0 0 auto', fontSize: 10, fontWeight: 600, color: T.onPrimary, background: T.primary, borderRadius: 4, padding: '0 5px', whiteSpace: 'nowrap' } }, tr('settings.fwdEditingBadge')) : null, React.createElement('span', { title: tr(f.direction === 'reverse' ? 'settings.fwdReverseHint' : 'settings.fwdLocalHint'), style: { flex: 1 }, @@ -2842,13 +3046,18 @@ window.__ModuleLoader__.load({ title: tr('settings.fwdLegacyHint'), style: { fontSize: 10, color: T.warn, border: '1px solid ' + T.border, borderRadius: 4, padding: '0 4px', whiteSpace: 'nowrap' }, }, tr('settings.fwdLegacyBadge')) : null, - React.createElement(RwCheckbox, { checked: !!f.autoStart, disabled: busy, title: tr('settings.fwdAutoHint'), label: tr('settings.fwdAuto'), onChange: (next) => requestFwdAutoStart({ kind: 'row', id: f.id }, next === true, f.direction) }), + React.createElement(RwCheckbox, { checked: !!f.autoStart, disabled: busy, title: tr('settings.fwdAutoHint'), label: tr('settings.fwdAuto'), onChange: (next) => requestFwdAutoStart({ kind: 'row', id: f.id }, next === true, f.direction) }), + React.createElement('button', { type: 'button', className: 'dsh-rw-btn', 'data-testid': 'fwd-edit', style: { ...buttonS, padding: '2px 8px' }, disabled: busy, title: tr('settings.fwdEditHint'), onClick: () => beginFwdEdit(f) }, tr('settings.fwdEdit')), f.active ? React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, padding: '2px 8px' }, disabled: busy, onClick: () => fwdAction('stop', f.id) }, tr('settings.fwdStop')) : React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, padding: '2px 8px' }, disabled: busy, onClick: () => fwdAction('start', f.id) }, busy ? tr('settings.fwdStarting') : tr('settings.fwdStart')), React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, padding: '2px 8px' }, disabled: busy, onClick: () => fwdAction('remove', f.id) }, tr('settings.fwdRemove'))) }) : null, - React.createElement('div', { style: { display: 'flex', gap: 6, alignItems: 'center', marginTop: 8, flexWrap: 'wrap' } }, + React.createElement('div', { + // Scroll anchor for 编辑: the form can sit below a long row list. + id: settingsId + '-fwd-form', + style: { display: 'flex', gap: 6, alignItems: 'center', marginTop: 8, flexWrap: 'wrap' }, + }, React.createElement('div', { role: 'group', 'aria-label': tr('settings.forwards'), style: { display: 'flex', alignItems: 'stretch', flex: '0 0 auto', height: 30, border: '1px solid ' + T.border, borderRadius: T.radius, overflow: 'hidden' }, @@ -2872,9 +3081,34 @@ window.__ModuleLoader__.load({ // the plugin's existing form pattern (.dsh-rw-settings-editor-actions // right-aligns its primary button), and it keeps 添加转发 from sitting // alone on a wrapped third line. - React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginTop: 8 } }, - React.createElement(RwCheckbox, { checked: fwdForm.autoStart, label: tr('settings.fwdAuto'), onChange: (next) => requestFwdAutoStart({ kind: 'form' }, next === true, fwdForm.direction) }), - React.createElement('button', { type: 'button', className: 'dsh-rw-btn dsh-rw-primary', style: primaryBtnS, onClick: fwdDefine, disabled: !fwdForm.listenPort, title: fwdForm.listenPort ? tr('settings.fwdAddHint') : tr('settings.fwdNeedsPort') }, tr('settings.fwdAdd'))), + React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginTop: 8, flexWrap: 'wrap' } }, + React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', minWidth: 0 } }, + // Which host this tunnel belongs to. Without it the form silently + // attached the forward to whatever machine happened to be + // connected, so a host that was not connected yet could never be + // given one. + React.createElement('label', { htmlFor: settingsId + '-fwd-host', style: { fontSize: 12, display: 'flex', gap: 4, alignItems: 'center', whiteSpace: 'nowrap', color: T.muted } }, tr('settings.fwdHost')), + React.createElement('select', { + id: settingsId + '-fwd-host', className: 'dsh-rw-input', 'data-testid': 'fwd-host', + value: fwdForm.machineId, + onChange: (e) => setFwdForm({ ...fwdForm, machineId: e.target.value }), + disabled: !machines.length, + title: tr('settings.fwdHostHint'), + 'aria-label': tr('settings.fwdHost'), + style: { ...inputS, maxWidth: 260, minWidth: 130, padding: '6px 8px' }, + }, + !machines.length ? React.createElement('option', { value: '' }, tr('settings.fwdHostEmpty')) : null, + machines.map((m) => React.createElement('option', { key: m.id, value: m.id }, + `${m.name || m.host} (${m.username || 'root'}@${m.host})` + (m.id === currentId ? ' · ' + tr('settings.fwdHostCurrent') : '')))), + React.createElement(RwCheckbox, { checked: fwdForm.autoStart, label: tr('settings.fwdAuto'), onChange: (next) => requestFwdAutoStart({ kind: 'form' }, next === true, fwdForm.direction) })), + React.createElement('div', { style: { display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' } }, + fwdEditId ? React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: buttonS, onClick: cancelFwdEdit, disabled: !!fwdBusy[fwdEditId] }, tr('settings.fwdCancelEdit')) : null, + React.createElement('button', { + type: 'button', className: 'dsh-rw-btn dsh-rw-primary', style: primaryBtnS, + onClick: () => (fwdEditId ? fwdSaveEdit() : fwdDefine()), + disabled: !fwdForm.listenPort || !fwdForm.machineId || !!fwdBusy[fwdEditId], + title: !fwdForm.listenPort ? tr('settings.fwdNeedsPort') : !fwdForm.machineId ? tr('settings.fwdHostNeeds') : (fwdEditId ? tr('settings.fwdEditHint') : tr('settings.fwdAddHint')), + }, fwdEditId ? tr('settings.fwdSaveChanges') : tr('settings.fwdAdd')))), React.createElement('div', { style: { opacity: 0.6, fontSize: 11, lineHeight: 1.5, marginTop: 6 } }, tr(fwdForm.direction === 'reverse' ? 'settings.fwdReverseHint' : 'settings.fwdLocalHint')), ) : null, @@ -3028,7 +3262,22 @@ window.__ModuleLoader__.load({ React.createElement('a', { href: 'https://github.com/flymysql/dsh-remote/issues/new', target: '_blank', rel: 'noopener noreferrer', style: { color: 'inherit' } }, tr('settings.feedback')), React.createElement('span', { style: { marginLeft: 'auto', opacity: 0.5 } }, 'dsh-remote v' + CLIENT_VERSION), ), - settingsMenu && HostMenu ? React.createElement(HostMenu, { open: true, portal: true, align: 'end', getAnchorRect: () => settingsMenu.anchor, items: [ { id: 'edit', label: tr('settings.edit') }, { id: 'delete', label: tr('settings.delete'), danger: true } ], onClose: () => setSettingsMenu(null), onSelect: id => { const machine = settingsMenu.machine; setSettingsMenu(null); if (id === 'edit') startEdit(machine); else if (id === 'delete') del(machine.id) } }) : null) + settingsMenu && HostMenu ? React.createElement(HostMenu, { + open: true, portal: true, + // Anchor the popup to the `...` button itself, right-aligned under it, + // and hand focus back to that button when the menu closes. + anchor: null, anchorRef: settingsMenu.anchorRef, + getAnchorRect: settingsMenu.getAnchorRect, + returnFocus: () => settingsMenu.el, + align: 'end', side: 'bottom', + // A discovered alias has no registry record to delete: 编辑 is the only + // action it can offer, exactly like the saved rows' first item. + items: settingsMenu.discovered + ? [ { id: 'edit', label: tr('settings.edit') } ] + : [ { id: 'edit', label: tr('settings.edit') }, { id: 'delete', label: tr('settings.delete'), danger: true } ], + onClose: () => setSettingsMenu(null), + onSelect: id => { const menu = settingsMenu; setSettingsMenu(null); if (id === 'edit') startEdit(menu.machine); else if (id === 'delete') del(menu.machine.id) }, + }) : null) } // ── Unified picker (fill the directory-flow holes) ─────────────────── @@ -5351,7 +5600,13 @@ window.__ModuleLoader__.load({ menu && HostMenu ? React.createElement(HostMenu, { open: true, portal: true, + // Pointer menu: a current host takes client coordinates (`anchorPoint`), + // an older one the equivalent zero-size rect. `contextual` adds the + // standard cursor clearance. + anchor: null, + anchorPoint: { x: menu.x, y: menu.y }, getAnchorRect: () => ({ left: menu.x, top: menu.y, right: menu.x, bottom: menu.y, width: 0, height: 0 }), + contextual: true, items: [ { id: 'open', label: menu.isDir ? tr('explorer.menuExpand') : tr('explorer.menuOpen') }, ...(!localWorkspaceSession(sessionId) ? [{ id: 'download', label: tr('explorer.menuDownload') }] : []), diff --git a/lib/forwards.js b/lib/forwards.js index 6979453..4dc7ea7 100644 --- a/lib/forwards.js +++ b/lib/forwards.js @@ -207,22 +207,34 @@ export class ForwardManager { } /** - * Patch an existing definition's mutable fields and persist it. Today that is - * just `autoStart` (the 自动重连 checkbox in the list). It does NOT start or - * stop the tunnel: the flag only decides whether a RUNNING forward is - * restored after its machine's connection drops. + * Patch an existing definition's mutable fields and persist it. + * + * Two callers share this: the row's 自动重连 checkbox patches only + * `autoStart`; the edit form sends the whole definition (direction, ports, + * target host, owning machine). Fields that are absent stay untouched — the + * route validates them first, so a typo never reaches this merge. + * + * It does NOT start or stop the tunnel. Changing a BIND of a running forward + * is refused by the route (the live socket would keep the old bind); toggling + * `autoStart` on a running forward is fine. * * @param {string} id - * @param {{autoStart?: boolean}} patch + * @param {{autoStart?: boolean, direction?: 'local'|'reverse', listenPort?: number, + * targetHost?: string, targetPort?: number, machineId?: string|null}} patch * @returns {object|null} the updated definition, or null when the id is unknown. */ - update(id, { autoStart } = {}) { + update(id, { autoStart, direction, listenPort, targetHost, targetPort, machineId } = {}) { const d = this.defs.find((x) => x.id === id) if (!d) return null if (typeof autoStart === 'boolean') { d.autoStart = autoStart delete d.needsReconsent } + if (direction === 'local' || direction === 'reverse') d.direction = direction + if (Number.isInteger(listenPort)) d.listenPort = listenPort + if (typeof targetHost === 'string' && targetHost) d.targetHost = targetHost + if (Number.isInteger(targetPort)) d.targetPort = targetPort + if (machineId !== undefined) d.machineId = machineId || null this._save() return d } diff --git a/lib/main.js b/lib/main.js index 7529461..433cc7d 100644 --- a/lib/main.js +++ b/lib/main.js @@ -3890,6 +3890,20 @@ export async function apply(ctx, config) { // alone, so a fresh registry stays "no choice yet" (not an // explicit none) and a previously-cleared registry stays cleared. saveMachines(machines, store.currentId, false) + // Editing the ACTIVE machine must re-point the live pool, not just the + // registry. The pool keeps the target it was APPLIED with, and every + // forward start / rw_* call dials through it — so without this the settings + // page showed the new address while 启动 still connected to the old one + // ("ssh: connect to host : Host is down"). setTarget() closes a live + // connection only when an identity field actually changed. + let poolWarning = '' + if (!ephemeral && store.currentId === rec.id) { + try { + await applyActiveMachine() + } catch (err) { + poolWarning = String((err && err.message) || err) + } + } // Issue #67: an EDITED connection identity (host/user/port) must // carry the machine's existing workspaces over — without this the // mirrors stayed bound to the old address and the user had to @@ -3941,6 +3955,7 @@ export async function apply(ctx, config) { ...(reboundMirrors ? { reboundMirrors } : {}), ...(warning ? { warning, warningDetail } : {}), ...(sshConfigWarning ? { sshConfigWarning } : {}), + ...(poolWarning ? { poolWarning } : {}), } } diff --git a/lib/routes-forwards.js b/lib/routes-forwards.js index 8ac35bf..bdedb70 100644 --- a/lib/routes-forwards.js +++ b/lib/routes-forwards.js @@ -37,27 +37,98 @@ export function createForwardRoutes({ sendJson, readBody, forwards, store, activ if (!Number.isInteger(targetPort) || targetPort < 1 || targetPort > 65535) { return sendJson(res, 400, { ok: false, error: 'targetPort 必须是 1–65535 的整数' }) } + // Which host the tunnel belongs to. The settings form names it + // explicitly (`machineId`): a forward can be DEFINED for a host that + // is not connected right now — it simply cannot start until that host + // is. Omitting the field keeps the historical behaviour: tag what the + // ACTIVE POOL is actually on (ephemeral included), not the registry's + // currentId, because rw_connect(save:false) keeps currentId on the old + // machine while the pool talks to the new one. + // + // An explicit id must be a real registry record: persisting a typo + // would create a forward that no machine can ever start and that no + // UI row can explain. + let machineId = typeof activeMachineId === 'function' ? activeMachineId() : store.currentId + if (Object.prototype.hasOwnProperty.call(body, 'machineId') && body.machineId !== null && body.machineId !== '') { + const wanted = String(body.machineId) + const known = Array.isArray(store.list) && store.list.some((m) => m && m.id === wanted) + if (!known) return sendJson(res, 404, { ok: false, error: 'machine not found', forwards: forwards.list() }) + machineId = wanted + } const d = forwards.define({ direction: body.direction === 'reverse' ? 'reverse' : 'local', listenPort, targetHost: body.targetHost || '127.0.0.1', targetPort, autoStart: !!body.autoStart, - // Tag what the ACTIVE POOL is actually on (ephemeral included), - // not the registry's currentId: rw_connect(save:false) keeps - // currentId on the old machine while the pool talks to the new one. - machineId: typeof activeMachineId === 'function' ? activeMachineId() : store.currentId, + machineId, }) return sendJson(res, 200, { ok: true, forward: d, forwards: forwards.list() }) } if (action === 'update') { - // Mutable fields of an existing definition — currently the 自动重连 - // checkbox shown on each row. Requires an explicit boolean: a - // missing field must not silently flip the flag to false. - if (typeof body.autoStart !== 'boolean') { - return sendJson(res, 400, { ok: false, error: 'autoStart 必须是布尔值' }) + // Partial patch: the row's 自动重连 checkbox sends only `autoStart`, + // the edit form sends the whole definition. Every field that IS + // present is validated; a missing field is left untouched (it must + // not silently reset anything). `autoStart`, when present, still has + // to be a real boolean. + const has = (k) => Object.prototype.hasOwnProperty.call(body, k) + const id = String(body.id || '') + const current = forwards.list().find((f) => f.id === id) + if (!current) return sendJson(res, 404, { ok: false, error: 'forward not found', forwards: forwards.list() }) + const patch = {} + if (has('autoStart')) { + if (typeof body.autoStart !== 'boolean') { + return sendJson(res, 400, { ok: false, error: 'autoStart 必须是布尔值' }) + } + patch.autoStart = body.autoStart + } + if (has('direction')) { + if (body.direction !== 'local' && body.direction !== 'reverse') { + return sendJson(res, 400, { ok: false, error: 'direction 只能是 local 或 reverse' }) + } + patch.direction = body.direction + } + if (has('listenPort')) { + const p = Number(body.listenPort) + if (!Number.isInteger(p) || p < 1 || p > 65535) { + return sendJson(res, 400, { ok: false, error: 'listenPort 必须是 1–65535 的整数' }) + } + patch.listenPort = p + } + if (has('targetPort')) { + // An empty target port means "same as the listen port", exactly + // like the add form. + const p = body.targetPort === '' || body.targetPort == null + ? (patch.listenPort !== undefined ? patch.listenPort : current.listenPort) + : Number(body.targetPort) + if (!Number.isInteger(p) || p < 1 || p > 65535) { + return sendJson(res, 400, { ok: false, error: 'targetPort 必须是 1–65535 的整数' }) + } + patch.targetPort = p + } + if (has('targetHost')) { + const host = String(body.targetHost || '').trim() || '127.0.0.1' + patch.targetHost = host + } + if (has('machineId')) { + if (body.machineId === null || body.machineId === '') { + patch.machineId = null + } else { + const wanted = String(body.machineId) + const known = Array.isArray(store.list) && store.list.some((m) => m && m.id === wanted) + if (!known) return sendJson(res, 404, { ok: false, error: 'machine not found', forwards: forwards.list() }) + patch.machineId = wanted + } + } + // A live tunnel keeps its OLD bind until it is torn down; editing it + // in place would show one port while the socket listens on another. + // Only the bind matters — 自动重连 may still be toggled while running. + const bindChanged = ['direction', 'listenPort', 'targetHost', 'targetPort', 'machineId'] + .some((k) => k in patch && patch[k] !== (current[k] === undefined ? null : current[k])) + if (current.active && bindChanged) { + return sendJson(res, 409, { ok: false, error: '先停止这条转发再修改监听/目标/主机', forwards: forwards.list() }) } - const d = forwards.update(String(body.id || ''), { autoStart: body.autoStart }) + const d = forwards.update(id, patch) if (!d) return sendJson(res, 404, { ok: false, error: 'forward not found', forwards: forwards.list() }) return sendJson(res, 200, { ok: true, forward: d, forwards: forwards.list() }) } diff --git a/test/forwards-host-ui.test.js b/test/forwards-host-ui.test.js new file mode 100644 index 0000000..53883fd --- /dev/null +++ b/test/forwards-host-ui.test.js @@ -0,0 +1,506 @@ +// The two settings-page holes behind "我新加的 host 没法配置转发": +// +// 1. The port-forward form had no host field at all. `define` tagged whatever +// machine happened to be connected, so a host that was not connected could +// never be given a tunnel — and there was no way to say "this forward is for +// that host". +// 2. A host added to ~/.ssh/config rendered in the host list WITHOUT any +// actions (only a probe), because only SAVED machines had the `...` menu. +// There was therefore no edit entry and no place to type the login password; +// that in turn made the host impossible to connect, hence impossible to +// forward through. +// +// Both defects are about which props the rendered controls end up with after a +// click, so this drives the REAL settings component with REAL React (same harness +// idea as settings-credentials-ui.test.js) instead of asserting on source text. + +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { fileURLToPath } from 'node:url' +import path from 'node:path' +import { fakeTimers } from './harness/fake-timers.js' +import { installTestDispatcher } from './harness/react-dispatcher.js' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const root = path.join(here, '..') +const require = createRequire(import.meta.url) +const React = require('react') +const src = readFileSync(path.join(root, 'lib', 'client.js'), 'utf8') + +const CURRENT = { + id: 'm-current', name: 'box', host: '10.0.0.9', port: 22, username: 'root', + passwordSet: true, passphraseSet: false, credentialBackend: 'plain', + useAgent: false, keyboardInteractive: false, useSshConfig: false, backend: 'native', + recentWorkspaces: [], +} +const OTHER = { + ...CURRENT, id: 'm-other', name: 'other', host: '10.0.0.10', +} +const SSH_HOST = { alias: '172.16.11.143', host: '172.16.11.143', user: 'kali', port: 22 } + +/** Load the client bundle, run apply(), expose the settings component and the + * request log. The fake host answers the three routes this page reads. */ +function mountClient(opts = {}) { + const list = [{ ...CURRENT }, { ...OTHER }] + const forwards = (opts.forwards || []).map((f) => ({ ...f })) + const calls = [] + const fetchStub = async (url, init) => { + const method = (init && init.method) || 'GET' + const body = init && init.body ? JSON.parse(init.body) : null + calls.push({ method, url: String(url), body }) + const reply = (obj) => ({ ok: true, status: 200, json: async () => obj }) + const u = String(url) + if (u.includes('/dsh-remote/machines')) { + if (method === 'POST') { + const id = body.id || 'm-adopted' + const rec = { + ...CURRENT, ...body, id, + passwordSet: !!body.password || (body.id ? CURRENT.passwordSet : false), + passphraseSet: false, credentialBackend: 'plain', + } + delete rec.password + const at = list.findIndex((m) => m.id === id) + if (at >= 0) list[at] = rec; else list.push(rec) + return reply({ ok: true, machine: rec, machines: list.map((m) => ({ ...m })), currentId: 'm-current' }) + } + return reply({ machines: list.map((m) => ({ ...m })), currentId: 'm-current' }) + } + if (u.includes('/dsh-remote/ssh-config')) { + return reply({ entries: [{ ...SSH_HOST }], file: '/home/u/.ssh/config' }) + } + if (u.includes('/dsh-remote/forwards')) { + if (method === 'POST') { + if (body.action === 'define') { + const forward = { + id: 'fwd-new', direction: body.direction, listenPort: body.listenPort, + targetHost: body.targetHost, targetPort: body.targetPort, + // A pre-#PR host half ignores the field and tags the ACTIVE machine. + machineId: opts.ignoreForwardHost ? 'm-current' : body.machineId, + autoStart: !!body.autoStart, active: false, + } + forwards.push(forward) + return reply({ ok: true, forward, forwards: forwards.map((f) => ({ ...f })) }) + } + const forward = forwards.find((f) => f.id === body.id) + if (body.action === 'update') { + // A pre-edit host half knows only 自动重连 and ignores the rest. + const keys = opts.ignoreForwardEdit ? ['autoStart'] : ['direction', 'listenPort', 'targetHost', 'targetPort', 'machineId', 'autoStart'] + for (const key of keys) { + if (key in body) forward[key] = body[key] + } + } else if (body.action === 'remove') { + const at = forwards.indexOf(forward); if (at >= 0) forwards.splice(at, 1) + } else if (body.action === 'start') forward.active = true + else if (body.action === 'stop') forward.active = false + return reply({ ok: true, forward, forwards: forwards.map((f) => ({ ...f })) }) + } + return reply({ forwards: forwards.map((f) => ({ ...f })) }) + } + return reply({}) + } + + let loaded = null + const timers = fakeTimers() + const sandbox = { + window: { + addEventListener: () => {}, + location: { protocol: 'http:', href: 'http://127.0.0.1:3080/' }, + localStorage: { getItem: () => null, setItem: () => {} }, + confirm: () => true, + setTimeout: timers.setTimeout, + clearTimeout: timers.clearTimeout, + __ModuleLoader__: { load: (m) => { loaded = m } }, + }, + document: { + head: { appendChild: () => {} }, + createElement: () => ({ style: {}, setAttribute: () => {}, appendChild: () => {} }), + getElementById: () => null, + }, + navigator: { clipboard: null, userAgent: 'node', languages: ['zh-CN'] }, + setTimeout: timers.setTimeout, clearTimeout: timers.clearTimeout, console, + fetch: fetchStub, + } + const requireStub = (id) => { + if (id === 'react') return React + if (id === '@deepseek-ai/dsh-client-ui-primitives') return { relativeTime: () => ({ unit: 'now', n: 0 }), ...(opts.primitives || {}) } + throw new Error('unexpected require: ' + id) + } + const run = new Function( + 'window', 'document', 'navigator', 'setTimeout', 'clearTimeout', 'console', 'fetch', 'require', `${src}\n//# sourceURL=lib/client.js`, + ) + run(sandbox.window, sandbox.document, sandbox.navigator, timers.setTimeout, timers.clearTimeout, console, fetchStub, requireStub) + + const mod = loaded.factory(requireStub) + let Page = null + const ctx = { + get(name) { + if (name === 'locale') return { register: () => {}, bind: () => (k) => k } + if (name === 'slots') { + return { + inject: (slot, fn) => { fn(); return () => {} }, + register: (decl, comp) => { if (comp && decl && decl.name === 'settings.section') Page = comp; return () => {} }, + get: () => [], + } + } + if (name === 'sessions') return { list: { getSnapshot: () => ({ byId: {} }) } } + return undefined + }, + effect(fn) { const d = fn(); return typeof d === 'function' ? d : () => {} }, + inject(names, cb) { if (names.every((n) => this.get(n) !== undefined)) cb(this) }, + on() {}, + logger: { warn: () => {}, info: () => {}, debug: () => {} }, + } + mod.apply(ctx) + assert.ok(Page, 'the settings section component must be registered') + return { Page, calls, list } +} + +/** Positional hook driver (same shape as settings-credentials-ui.test.js). */ +function makeDriver(Page) { + const state = [] + const refs = new Map() + const deps = new Map() + const cleanups = [] + let cursor = 0 + let pending = [] + + const dispatcher = { + useState(init) { + const i = cursor++ + if (!(i in state)) state[i] = typeof init === 'function' ? init() : init + return [state[i], (v) => { state[i] = typeof v === 'function' ? v(state[i]) : v }] + }, + // Dependency-aware, unlike the older rigs: the forwards form is filled by an + // effect that fires only after /machines answers, and a run-once model would + // never exercise the re-render the user actually sees. + useEffect(fn, list) { + const i = cursor++ + const prev = deps.get(i) + const changed = !prev || !list || list.length !== prev.length || list.some((d, k) => !Object.is(d, prev[k])) + if (changed) { deps.set(i, list || []); pending.push(fn) } + }, + useRef(v) { + const i = cursor++ + if (!refs.has(i)) refs.set(i, { current: v }) + return refs.get(i) + }, + useCallback(fn) { cursor++; return fn }, + useMemo(fn) { cursor++; return fn() }, + useLayoutEffect() {}, useInsertionEffect() {}, + useContext() { return {} }, + useReducer(_r, init) { cursor++; return [init, () => {}] }, + useDebugValue() {}, useId() { cursor++; return 'id' + cursor }, + useTransition() { cursor++; return [false, (f) => f && f()] }, + useDeferredValue(v) { cursor++; return v }, + useImperativeHandle() {}, + } + installTestDispatcher(React, dispatcher) + + const settle = async () => { + const renderPage = () => { + cursor = 0 + pending = [] + let tree = Page({}) + while (tree && typeof tree === 'object' && !Array.isArray(tree) && typeof tree.type === 'function') { + tree = tree.type(tree.props) + } + return tree + } + let tree = null + for (let pass = 0; pass < 8; pass++) { + tree = renderPage() + const batch = pending + if (!batch.length) return tree + for (const fn of batch) { + const c = fn() + if (typeof c === 'function') cleanups.push(c) + } + await new Promise((r) => setTimeout(r, 0)) + await new Promise((r) => setTimeout(r, 0)) + } + return tree + } + const dispose = () => { for (const c of cleanups.splice(0)) { try { c() } catch {} } } + return { settle, dispose } +} + +function elements(tree, out = []) { + if (Array.isArray(tree)) { for (const t of tree) elements(t, out); return out } + if (!tree || typeof tree !== 'object') return out + if (tree.props === undefined && tree.$$typeof === undefined) return out + out.push(tree) + if (tree.props && tree.props.children !== undefined) elements(tree.props.children, out) + return out +} + +function textOf(node) { + if (node == null || node === false || node === true) return '' + if (typeof node === 'string' || typeof node === 'number') return String(node) + if (Array.isArray(node)) return node.map(textOf).join('') + if (typeof node === 'object' && node.props) return textOf(node.props.children) + return '' +} + +function buttonByText(tree, re) { + return elements(tree).filter((el) => el.type === 'button' && re.test(textOf(el).trim())) +} + +/** Flush the promise chains started by a click (fetch → setState → refresh). */ +async function flush() { + for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0)) +} + +test('the forward form names its host instead of inheriting the connected one', async () => { + const { Page, calls } = mountClient() + const { settle, dispose } = makeDriver(Page) + try { + let tree = await settle() + // The forwards panel is collapsed by default; open it the way a user does. + const toggle = buttonByText(tree, /端口转发/) + assert.equal(toggle.length, 1, 'the forwards section toggle must render') + toggle[0].props.onClick() + tree = await settle() + + const select = elements(tree).find((el) => el.type === 'select' && el.props['data-testid'] === 'fwd-host') + assert.ok(select, 'the add-forward form must render a host selector') + assert.equal(select.props.value, 'm-current', 'it defaults to the currently connected machine') + const options = elements(select).filter((el) => el.type === 'option').map(textOf) + assert.ok(options.some((t) => /box/.test(t) && /当前/.test(t)), `current host must be marked, got: ${options.join(' | ')}`) + assert.ok(options.some((t) => /other/.test(t)), 'every saved machine is selectable, not just the connected one') + + // Pick the host that is NOT connected, then fill the port and add. + select.props.onChange({ target: { value: 'm-other' } }) + tree = await settle() + const listen = elements(tree).find((el) => el.type === 'input' && el.props.placeholder === '监听端口') + assert.ok(listen, 'the listen-port field must render') + listen.props.onChange({ target: { value: '9000' } }) + tree = await settle() + + const add = buttonByText(tree, /^添加转发$/) + assert.equal(add.length, 1, 'the add button must render') + assert.equal(add[0].props.disabled, false, 'a chosen host + port must enable 添加转发') + add[0].props.onClick() + await flush() + await settle() + + const posted = calls.find((c) => c.method === 'POST' && c.url.includes('/dsh-remote/forwards')) + assert.ok(posted, 'a define request must be sent') + assert.equal(posted.body.machineId, 'm-other', 'the selected host must own the definition') + assert.equal(posted.body.listenPort, 9000) + } finally { dispose() } +}) + +test('an unsaved ~/.ssh/config host has an edit entry that can save a login password', async () => { + // A host Menu primitive present: this is the production path, where the + // discovered row's `...` opens the same portaled menu as a saved machine. + const Menu = ({ items, onSelect }) => React.createElement('div', { 'data-fake-menu': true }, + items.map((it) => React.createElement('button', { key: it.id, 'data-menu-item': it.id, onClick: () => onSelect(it.id) }, it.label))) + const { Page, calls, list } = mountClient({ primitives: { Menu } }) + const { settle, dispose } = makeDriver(Page) + try { + let tree = await settle() + // The discovered row now carries the SAME `...` menu trigger as a saved + // machine (it used to be a bare text button that turned into `...` after the + // first save). + const triggers = elements(tree).filter((el) => el.type === 'button' && /保存为机器/.test(String(el.props['aria-label']))) + assert.equal(triggers.length, 1, `exactly one menu trigger (the SSH-config host), got ${triggers.length}`) + assert.equal(triggers[0].props['aria-haspopup'], 'menu', 'it must be a menu, not a one-off button') + + const triggerEl = { focus() {}, getBoundingClientRect: () => ({ top: 7, left: 3, right: 13, bottom: 27, width: 10, height: 20 }) } + triggers[0].props.onClick({ currentTarget: triggerEl }) + tree = await settle() + // The shared host menu mounts as a function component; assert on the props + // it is handed (anchor + items + handler) and drive its selection. + const menu = elements(tree).find((el) => el.type === Menu) + assert.ok(menu, 'the `...` trigger must open the shared host menu') + assert.equal(menu.props.anchor, null) + assert.equal(menu.props.anchorRef.current, triggerEl, + 'the menu must be anchored to the button that was pressed, not to a stale rect') + assert.equal(typeof menu.props.returnFocus, 'function', 'closing must return focus to the trigger') + // Pre-0.2.2 hosts only know the rect prop; they must keep working too. + assert.equal(typeof menu.props.getAnchorRect, 'function') + assert.equal(menu.props.getAnchorRect().top, 7, 'the legacy rect comes from the pressed button') + assert.deepEqual(menu.props.items.map((it) => it.id), ['edit'], + 'a discovered alias offers 编辑 only (there is no registry record to delete)') + menu.props.onSelect('edit') + tree = await settle() + + // The machine form is now open, prefilled as an ALIAS. + const hostInput = elements(tree).find((el) => el.type === 'input' && el.props.value === SSH_HOST.alias) + assert.ok(hostInput, 'the form must be prefilled with the SSH-config host') + const pwd = elements(tree).find((el) => el.type === 'input' && el.props.type === 'password' && /SSH 密码/.test(String(el.props.placeholder))) + assert.ok(pwd, 'the form must offer the login-password field for this host') + pwd.props.onChange({ target: { value: 'kali-pw' } }) + tree = await settle() + + const save = buttonByText(tree, /^保存$/) + assert.equal(save.length, 1, 'the save button must render') + save[0].props.onClick() + await flush() + tree = await settle() + + const posted = calls.find((c) => c.method === 'POST' && c.url.includes('/dsh-remote/machines')) + assert.ok(posted, 'saving must create a machine record') + assert.equal(posted.body.action, 'add', 'a discovered host is ADDED, never silently rewritten on disk') + assert.equal(posted.body.host, SSH_HOST.alias) + assert.equal(posted.body.useSshConfig, true, 'the alias stays the source of truth') + assert.equal(posted.body.backend, 'openssh', 'the user\'s own ssh interprets the Host block') + assert.equal(posted.body.password, 'kali-pw', 'the password the user typed must be saved') + assert.ok(list.some((m) => m.host === SSH_HOST.alias), 'the adopted host shows up as a saved machine') + } finally { dispose() } +}) +test('a host half that ignores the host field cannot leave the tunnel on the wrong machine', async () => { + const { Page, calls } = mountClient({ ignoreForwardHost: true }) + const { settle, dispose } = makeDriver(Page) + try { + let tree = await settle() + buttonByText(tree, /端口转发/)[0].props.onClick() + tree = await settle() + const select = elements(tree).find((el) => el.type === 'select' && el.props['data-testid'] === 'fwd-host') + select.props.onChange({ target: { value: 'm-other' } }) + tree = await settle() + elements(tree).find((el) => el.type === 'input' && el.props.placeholder === '监听端口').props.onChange({ target: { value: '9001' } }) + tree = await settle() + buttonByText(tree, /^添加转发$/)[0].props.onClick() + await flush() + tree = await settle() + + // The wrong attachment is detected and undone instead of being shown as success. + const removed = calls.find((c) => c.method === 'POST' && c.url.includes('/dsh-remote/forwards') && c.body && c.body.action === 'remove') + assert.ok(removed, 'the mis-attached definition must be removed') + assert.equal(removed.body.id, 'fwd-new') + assert.ok(elements(tree).some((el) => /重启 DSH/.test(textOf(el))), + 'the user must be told why and what to do (restart DSH)') + } finally { dispose() } +}) + +test('an existing forward can be edited (including its host) instead of deleted and re-added', async () => { + const existing = { + id: 'f1', direction: 'local', listenPort: 9000, targetHost: '127.0.0.1', + targetPort: 8080, machineId: 'm-current', autoStart: false, active: false, + } + const { Page, calls } = mountClient({ forwards: [existing] }) + const { settle, dispose } = makeDriver(Page) + try { + let tree = await settle() + buttonByText(tree, /端口转发/)[0].props.onClick() + tree = await settle() + + const edit = elements(tree).filter((el) => el.props && el.props['data-testid'] === 'fwd-edit') + assert.equal(edit.length, 1, 'every forward row exposes 编辑') + assert.equal(edit[0].props.disabled, false, 'an inactive forward can be edited') + edit[0].props.onClick() + tree = await settle() + + // Prefilled from the definition, and the primary action says it saves. + const listen = elements(tree).find((el) => el.type === 'input' && el.props.placeholder === '监听端口') + assert.equal(listen.props.value, '9000', 'the form must be prefilled with the existing definition') + const select0 = elements(tree).find((el) => el.type === 'select' && el.props['data-testid'] === 'fwd-host') + assert.equal(select0.props.value, 'm-current') + assert.equal(buttonByText(tree, /^保存修改$/).length, 1, '添加转发 becomes 保存修改 while editing') + assert.equal(buttonByText(tree, /^取消$/).length, 1, 'editing can be cancelled') + + // The edited RECORD stays identifiable through the highlighted row (plus its + // 编辑中 badge) — no extra banner above the form. + const highlighted = elements(tree).filter((el) => el.props && el.props['data-fwd-editing'] === 'true') + assert.equal(highlighted.length, 1, 'exactly the record being edited is highlighted') + assert.match(textOf(highlighted[0]), /编辑中/, 'the highlighted row carries the badge') + + listen.props.onChange({ target: { value: '9100' } }) + tree = await settle() + // Re-read after the re-render: handlers close over the form they rendered. + elements(tree).find((el) => el.type === 'select' && el.props['data-testid'] === 'fwd-host') + .props.onChange({ target: { value: 'm-other' } }) + tree = await settle() + + buttonByText(tree, /^保存修改$/)[0].props.onClick() + await flush() + tree = await settle() + + const update = calls.find((c) => c.method === 'POST' && c.body && c.body.action === 'update') + assert.ok(update, 'an update request must be sent') + assert.equal(update.body.id, 'f1') + assert.equal(update.body.listenPort, 9100, 'the new listen port is persisted') + assert.equal(update.body.targetPort, 8080, 'untouched fields keep their values') + assert.equal(update.body.machineId, 'm-other', 'the owning host can be changed too') + assert.equal(calls.some((c) => c.body && c.body.action === 'define'), false, + 'editing must not create a second definition') + assert.match(textOf(tree), /9100/, 'the row shows the updated definition') + assert.equal(elements(tree).filter((el) => el.props && el.props['data-fwd-editing'] === 'true').length, 0, + 'the highlight must clear once the edit is saved') + } finally { dispose() } +}) + +test('editing a RUNNING forward stops it, patches it and starts it again', async () => { + const existing = { + id: 'f1', direction: 'local', listenPort: 9000, targetHost: '127.0.0.1', + targetPort: 8080, machineId: 'm-current', autoStart: true, active: true, + } + const { Page, calls } = mountClient({ forwards: [existing] }) + const { settle, dispose } = makeDriver(Page) + try { + let tree = await settle() + buttonByText(tree, /端口转发/)[0].props.onClick() + tree = await settle() + elements(tree).find((el) => el.props && el.props['data-testid'] === 'fwd-edit').props.onClick() + tree = await settle() + + elements(tree).find((el) => el.type === 'input' && el.props.placeholder === '目标端口') + .props.onChange({ target: { value: '9090' } }) + tree = await settle() + buttonByText(tree, /^保存修改$/)[0].props.onClick() + await flush() + await settle() + + const actions = calls.filter((c) => c.method === 'POST' && c.url.includes('/dsh-remote/forwards')) + .map((c) => c.body && c.body.action) + // A live socket keeps its old bind, so the edit is applied to a stopped + // definition and the tunnel is put back afterwards. + assert.deepEqual(actions, ['stop', 'update', 'start']) + assert.equal(calls.find((c) => c.body && c.body.action === 'update').body.targetPort, 9090) + } finally { dispose() } +}) + +test('a host half that cannot edit forwards does not report a silent success', async () => { + const existing = { + id: 'f1', direction: 'local', listenPort: 9000, targetHost: '127.0.0.1', + targetPort: 8080, machineId: 'm-current', autoStart: false, active: false, + } + const { Page, calls } = mountClient({ forwards: [existing], ignoreForwardEdit: true }) + const { settle, dispose } = makeDriver(Page) + try { + let tree = await settle() + buttonByText(tree, /端口转发/)[0].props.onClick() + tree = await settle() + elements(tree).find((el) => el.props && el.props['data-testid'] === 'fwd-edit').props.onClick() + tree = await settle() + elements(tree).find((el) => el.type === 'input' && el.props.placeholder === '监听端口') + .props.onChange({ target: { value: '9100' } }) + tree = await settle() + buttonByText(tree, /^保存修改$/)[0].props.onClick() + await flush() + tree = await settle() + + assert.ok(elements(tree).some((el) => /没能保存这些修改/.test(textOf(el))), + 'an update the host did not apply must not look saved') + // The editor stays open so the user can retry after restarting DSH. + assert.equal(buttonByText(tree, /^保存修改$/).length, 1) + // And the old definition is still the one in the list (never a second one). + assert.equal(calls.some((c) => c.body && c.body.action === 'define'), false) + } finally { dispose() } +}) + +test('host menus carry the current CSS-anchor props, not only the legacy rect', () => { + // DSH 0.2.2-alpha.2 replaced getAnchorRect with anchorRef / anchorPoint. A host + // menu that passes ONLY the rect is silently left unattached (this is how the + // edit/delete popup ended up away from the `...` button, and the explorer + // context menu away from the pointer). Both APIs are passed for old hosts. + assert.match(src, /anchorRef: settingsMenu\.anchorRef/, + 'the settings menu must anchor to the pressed button element') + assert.match(src, /anchorPoint: \{ x: menu\.x, y: menu\.y \}/, + 'the explorer context menu must anchor to the pointer') + assert.match(src, /getAnchorRect: settingsMenu\.getAnchorRect/, + 'older hosts still get the rect fallback') +}) diff --git a/test/forwards-lifecycle.test.js b/test/forwards-lifecycle.test.js index 1150bea..e023ae0 100644 --- a/test/forwards-lifecycle.test.js +++ b/test/forwards-lifecycle.test.js @@ -319,6 +319,83 @@ test('unknown forward ids and actions are refused with 404/400 and a reason', as }) }) +test('a forward can be defined for a host that is not the connected one', async () => { + const first = machine({ host: '10.0.0.9' }) + const second = machine({ host: '10.0.0.10', name: 'other' }) + const host = await createHost({ machines: [first, second], currentId: first.id }) + try { + // The settings form names the host explicitly. Defining is allowed before + // that host is ever dialed: the tunnel becomes startable once it is. + const defined = await post(host, { + action: 'define', machineId: second.id, listenPort: await freePort(), targetHost: '127.0.0.1', targetPort: 22, + }) + assert.equal(defined.status, 200, defined.raw) + assert.equal(defined.json.forward.machineId, second.id, 'the NAMED host must own the definition') + assert.equal((await host.call('/dsh-remote/forwards', { method: 'GET' })).json.forwards + .find((f) => f.id === defined.json.forward.id).machineId, second.id, + 'a later GET (and a restart) must keep the owner') + + // Starting it while another machine is active must be refused — otherwise + // the tunnel would silently run through the WRONG connection. + const started = await post(host, { action: 'start', id: defined.json.forward.id }) + assert.equal(started.json.ok, false) + assert.match(String(started.json.error), /另一台机器/) + + // A typo must never persist a definition that no machine can start. + const unknown = await post(host, { + action: 'define', machineId: 'm-does-not-exist', listenPort: await freePort(), targetPort: 22, + }) + assert.equal(unknown.status, 404) + assert.match(String(unknown.json.error), /machine not found/) + } finally { await host.dispose() } +}) + +test('an existing definition can be edited; a live tunnel refuses bind changes', async () => { + const echo = await echoServer() + try { + await withForwards(async ({ host }) => { + const started = await startOnFreePort(host, post, echo.port) + assert.equal(started.started.json.ok, true, `start failed: ${started.started.raw}`) + const fwd = started.fwd + + // The socket still listens on the OLD port, so "edited" and "listening" + // would disagree: a bind change on a live tunnel is refused. + const blocked = await post(host, { action: 'update', id: fwd.id, listenPort: started.listenPort + 1 }) + assert.equal(blocked.status, 409) + assert.match(String(blocked.json.error), /先停止/) + + // 自动重连 is not a bind and stays editable while running. + const auto = await post(host, { action: 'update', id: fwd.id, autoStart: true }) + assert.equal(auto.status, 200) + assert.equal(auto.json.forward.autoStart, true) + + // Stop, then edit every editable field through one partial patch. + await post(host, { action: 'stop', id: fwd.id }) + const nextPort = await freePort() + const updated = await post(host, { + action: 'update', id: fwd.id, direction: 'reverse', listenPort: nextPort, + targetHost: '127.0.0.1', targetPort: 22, autoStart: false, + }) + assert.equal(updated.status, 200, updated.raw) + assert.equal(updated.json.forward.direction, 'reverse') + assert.equal(updated.json.forward.listenPort, nextPort) + assert.equal(updated.json.forward.targetPort, 22) + assert.equal(updated.json.forward.autoStart, false) + const listed = (await host.call('/dsh-remote/forwards', { method: 'GET' })).json.forwards + .find((f) => f.id === fwd.id) + assert.equal(listed.listenPort, nextPort, 'the edit is persisted for a later start') + assert.equal(listed.targetPort, 22) + + // Field validation still runs for every supplied value. + assert.equal((await post(host, { action: 'update', id: fwd.id, listenPort: 0 })).status, 400) + assert.equal((await post(host, { action: 'update', id: fwd.id, direction: 'sideways' })).status, 400) + assert.equal((await post(host, { action: 'update', id: fwd.id, targetPort: 70000 })).status, 400) + assert.equal((await post(host, { action: 'update', id: fwd.id, machineId: 'nope' })).status, 404) + assert.equal((await post(host, { action: 'update', id: 'nope', autoStart: true })).status, 404) + }) + } finally { await echo.close() } +}) + // ── autoStart semantics + concurrent starts ──────────────────────────────── // // 自动重连 means RESTORE: a forward that was running when the connection diff --git a/test/machine-edit-pool.test.js b/test/machine-edit-pool.test.js new file mode 100644 index 0000000..6926822 --- /dev/null +++ b/test/machine-edit-pool.test.js @@ -0,0 +1,56 @@ +// Regression: editing the machine the pool is CURRENTLY bound to must re-point +// the live pool, not just the registry file. +// +// The pool keeps the target it was APPLIED with, and forwards.start() / every +// rw_* call dials through it. The settings save path only wrote the registry and +// rebound mirrors, so after changing a machine's host the settings page showed +// the new address while 启动 still connected to the old one — exactly the +// "modified the host, saved, but 启动 says ssh: connect to host : Host is +// down" report. +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { createHost, machine } from './harness/plugin-host.js' + +const addressOf = async (host) => (await host.call('/dsh-remote/status', { method: 'GET' })).json + +test('editing the ACTIVE machine re-points the live pool at the new host', async () => { + const rec = machine({ host: 'alias-old', useSshConfig: true, backend: 'openssh', username: 'kali' }) + const host = await createHost({ machines: [rec], currentId: rec.id }) + try { + const cur = await host.call('/dsh-remote/current', { body: { id: rec.id } }) + assert.equal(cur.json.ok, true, cur.raw) + assert.equal((await addressOf(host)).host, 'alias-old', 'the pool starts on the saved address') + + const saved = await host.call('/dsh-remote/machines', { + body: { + action: 'update', id: rec.id, name: 'kali', host: 'alias-new', + port: 22, username: 'kali', useSshConfig: true, backend: 'openssh', + }, + }) + assert.equal(saved.status, 200, saved.raw) + assert.equal(saved.json.poolWarning, undefined, 're-pointing must not fail silently') + + // Immediately, before any /current or reconnect: the pool dials the new host. + const st = await addressOf(host) + assert.equal(st.host, 'alias-new', 'the live pool must use the edited address, not the one it was applied with') + assert.equal(st.currentId, rec.id) + } finally { await host.dispose() } +}) + +test('editing a machine that is NOT active leaves the active pool untouched', async () => { + const active = machine({ host: 'alias-active', useSshConfig: true, backend: 'openssh' }) + const other = machine({ host: 'alias-other', useSshConfig: true, backend: 'openssh' }) + const host = await createHost({ machines: [active, other], currentId: active.id }) + try { + await host.call('/dsh-remote/current', { body: { id: active.id } }) + const saved = await host.call('/dsh-remote/machines', { + body: { + action: 'update', id: other.id, host: 'alias-other-2', + port: 22, username: 'kali', useSshConfig: true, backend: 'openssh', + }, + }) + assert.equal(saved.status, 200, saved.raw) + assert.equal((await addressOf(host)).host, 'alias-active', + 'saving a standby machine must not hijack the active connection') + } finally { await host.dispose() } +}) \ No newline at end of file diff --git a/test/settings-render.test.js b/test/settings-render.test.js index 45045d2..f87f35d 100644 --- a/test/settings-render.test.js +++ b/test/settings-render.test.js @@ -353,10 +353,17 @@ test('no backup i18n key survives the capability removal', () => { }) -test('host menus use the real getAnchorRect contract, not anchorPoint', () => { - assert.doesNotMatch(src, /anchorPoint\s*:/, 'the host bundle does not accept anchorPoint') - assert.match(src, /settingsMenu && HostMenu[\s\S]*getAnchorRect: \(\) => settingsMenu\.anchor/, - 'settings menus must use the button DOMRect captured on click') +test('host menus carry the current CSS-anchor contract, plus the legacy rect', () => { + // DSH 0.2.2-rc.2 (deepseek-harness commit 2c990f0b14, "position floating + // panels with CSS anchors") REPLACED `getAnchorRect` with `anchorRef` (the + // trigger element) and `anchorPoint` (client coordinates). On such a host a + // menu given only the rect is silently placed elsewhere — that is why the + // 编辑/删除 popup and the explorer context menu were detached from their + // trigger. Older hosts only know the rect, so both are passed and each host + // ignores the prop it does not implement. + assert.match(src, /anchorRef: settingsMenu\.anchorRef/, 'settings menus anchor to the pressed element') + assert.match(src, /anchorPoint: \{ x: menu\.x, y: menu\.y \}/, 'context menus anchor to the pointer') + assert.match(src, /getAnchorRect: settingsMenu\.getAnchorRect/, 'legacy hosts keep the button rect') assert.match(src, /getAnchorRect: \(\) => \(\{ left: menu\.x, top: menu\.y, right: menu\.x, bottom: menu\.y, width: 0, height: 0 \}\)/, - 'context menus must compute a zero-size rect at the pointer') + 'legacy context menus keep the zero-size pointer rect') })