dsh-remote-go 0.3.2 → 0.3.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/dist/client.js CHANGED
@@ -717,13 +717,29 @@ window.__ModuleLoader__.load({
717
717
  cardStopRemote: ['关闭', 'Stop'],
718
718
  cardStopping: ['正在关闭…', 'Stopping…'],
719
719
  cardStopRemoteName: ['关闭远端 DSH', 'Stop the remote DSH'],
720
- stopRemoteTitle: ['关闭远端 DSH?', 'Stop the remote DSH?'],
720
+ // One confirmation component for the three link actions; the host name and the consequence difference are the point.
721
+ stopRemoteTitle: ['关闭「{name}」的远端 DSH?', 'Stop the remote DSH on "{name}"?'],
721
722
  stopRemoteBody: [
722
- '会停止远端进程并断开连接;配置与凭据保留,可随时重连。',
723
- 'Stops the remote process and disconnects. Settings and credentials are kept, so you can reconnect later.',
723
+ '会停止「{name}」上的远端 DSH 并断开连接;远端正在进行的任务会被终止。',
724
+ 'This stops the remote DSH on "{name}" and disconnects. Remote tasks in progress will be terminated.',
724
725
  ],
725
726
  stopRemoteConfirm: ['关闭', 'Stop'],
726
727
  stopRemoteBusy: ['正在关闭…', 'Stopping…'],
728
+ restartRemoteTitle: ['重启「{name}」的远端 DSH?', 'Restart the remote DSH on "{name}"?'],
729
+ restartRemoteBody: [
730
+ '会重启「{name}」的远端 DSH(换新端口),正在进行中的远端任务会被终止。',
731
+ 'This restarts the remote DSH on "{name}" on a new port. Remote tasks in progress will be terminated.',
732
+ ],
733
+ restartRemoteConfirm: ['重启', 'Restart'],
734
+ restartRemoteBusy: ['正在重启…', 'Restarting…'],
735
+ disconnectRemoteTitle: ['断开与「{name}」的连接?', 'Disconnect from "{name}"?'],
736
+ disconnectRemoteBody: [
737
+ '只断开与「{name}」的链路,远端 DSH 继续运行,之后可以重连。',
738
+ 'This only drops the link to "{name}". The remote DSH keeps running, and you can reconnect later.',
739
+ ],
740
+ disconnectRemoteConfirm: ['断开', 'Disconnect'],
741
+ disconnectRemoteBusy: ['正在断开…', 'Disconnecting…'],
742
+ thisHost: ['这台主机', 'this host'],
727
743
  cardDiagnose: ['诊断', 'Diagnose'],
728
744
  cardEdit: ['编辑', 'Edit'],
729
745
  cardDelete: ['删除', 'Delete'],
@@ -2708,22 +2724,55 @@ window.__ModuleLoader__.load({
2708
2724
  box('p', 'drg-paragraph', props.body),
2709
2725
  )
2710
2726
  }
2711
- function StopRemoteDialog(props) {
2727
+ const HOST_ACTION_DIALOGS = {
2728
+ stop: {
2729
+ title: 'stopRemoteTitle',
2730
+ body: 'stopRemoteBody',
2731
+ confirm: 'stopRemoteConfirm',
2732
+ busy: 'stopRemoteBusy',
2733
+ testId: 'stop-remote-dialog',
2734
+ prefix: 'stop-remote',
2735
+ },
2736
+ restart: {
2737
+ title: 'restartRemoteTitle',
2738
+ body: 'restartRemoteBody',
2739
+ confirm: 'restartRemoteConfirm',
2740
+ busy: 'restartRemoteBusy',
2741
+ testId: 'restart-remote-dialog',
2742
+ prefix: 'restart-remote',
2743
+ },
2744
+ disconnect: {
2745
+ title: 'disconnectRemoteTitle',
2746
+ body: 'disconnectRemoteBody',
2747
+ confirm: 'disconnectRemoteConfirm',
2748
+ busy: 'disconnectRemoteBusy',
2749
+ testId: 'disconnect-dialog',
2750
+ prefix: 'disconnect',
2751
+ },
2752
+ }
2753
+ function HostActionDialog(props) {
2712
2754
  const t = translatorOf(props)
2755
+ const kind = props.kind && HOST_ACTION_DIALOGS[props.kind] ? props.kind : 'stop'
2756
+ const spec = HOST_ACTION_DIALOGS[kind]
2757
+ const rawName = typeof props.hostName === 'string' ? props.hostName.trim() : ''
2758
+ const name = rawName === '' ? t('thisHost') : rawName
2713
2759
  const busy = props.busy === true
2714
2760
  return h(ConfirmDialog, {
2715
- title: t('stopRemoteTitle'),
2716
- body: t('stopRemoteBody'),
2717
- confirmLabel: busy ? t('stopRemoteBusy') : t('stopRemoteConfirm'),
2761
+ title: t(spec.title, { name }),
2762
+ body: t(spec.body, { name }),
2763
+ confirmLabel: busy ? t(spec.busy) : t(spec.confirm),
2718
2764
  cancelLabel: t('cancel'),
2719
2765
  busy,
2720
- testId: 'stop-remote-dialog',
2721
- confirmTestId: 'stop-remote-confirm',
2722
- cancelTestId: 'stop-remote-cancel',
2766
+ testId: spec.testId,
2767
+ confirmTestId: spec.prefix + '-confirm',
2768
+ cancelTestId: spec.prefix + '-cancel',
2723
2769
  onConfirm: props.onConfirm,
2724
2770
  onCancel: props.onCancel,
2725
2771
  })
2726
2772
  }
2773
+ function StopRemoteDialog(props) {
2774
+ return h(HostActionDialog, { ...props, kind: 'stop' })
2775
+ }
2727
2776
  function LoadingBlock(props) {
2728
2777
  const t = translatorOf(props)
2729
2778
  return box('div', 'drg-loading', h(Spinner, { size: 20 }), h('span', null, props.label || t('loading')))
@@ -2777,8 +2826,8 @@ window.__ModuleLoader__.load({
2777
2826
  }
2778
2827
  const iconButton = (testId, icon, label, callback, disabled) =>
2779
2828
  h(IconButton, { icon, label, testId, onClick: fire(callback), disabled })
2780
- const ghost = (testId, label, callback, disabled, ariaLabel) =>
2781
- h(Button, { variant: 'ghost', testId, ariaLabel, onClick: fire(callback), disabled }, label)
2829
+ const ghost = (testId, label, callback, disabled, ariaLabel, variant) =>
2830
+ h(Button, { variant: variant || 'ghost', testId, ariaLabel, onClick: fire(callback), disabled }, label)
2782
2831
  const stripText = meta.strip === 'alert' ? t('errorReason', { detail: reason || t(meta.hint) }) : t(meta.hint)
2783
2832
  const stripDiagnose = h(
2784
2833
  'button',
@@ -2861,6 +2910,8 @@ window.__ModuleLoader__.load({
2861
2910
  props.onRestart,
2862
2911
  linkBusy,
2863
2912
  t('cardRestartName'),
2913
+ // Restart kills the running remote tasks: the same danger treatment as stop, never a silent click.
2914
+ 'danger',
2864
2915
  )
2865
2916
  : null,
2866
2917
  stopAvailable
@@ -2870,6 +2921,7 @@ window.__ModuleLoader__.load({
2870
2921
  props.onStopRemote,
2871
2922
  linkBusy,
2872
2923
  t('cardStopRemoteName'),
2924
+ 'danger',
2873
2925
  )
2874
2926
  : null,
2875
2927
  meta.retry === true ? ghost('host-reconnect', t('cardReconnect'), props.onReconnect, busy) : null,
@@ -2908,21 +2960,6 @@ window.__ModuleLoader__.load({
2908
2960
  const visibleHosts = hosts.filter((host) => Boolean(host))
2909
2961
  const connected = hosts.filter((host) => host && host.status === 'connected').length
2910
2962
  const busyHostId = props.busyHostId || null
2911
- const [pendingStop, setPendingStop] = useState(null)
2912
- const [stopBusy, setStopBusy] = useState(false)
2913
- const requestStop = (host) => {
2914
- if (host) setPendingStop(host)
2915
- }
2916
- const confirmStop = () => {
2917
- if (pendingStop === null || stopBusy) return
2918
- const host = pendingStop
2919
- setStopBusy(true)
2920
- const settle = () => {
2921
- setStopBusy(false)
2922
- setPendingStop(null)
2923
- }
2924
- Promise.resolve(typeof props.onStopRemote === 'function' ? props.onStopRemote(host) : null).then(settle, settle)
2925
- }
2926
2963
  const card = (host) =>
2927
2964
  h(HostCard, {
2928
2965
  key: host.id,
@@ -2935,7 +2972,7 @@ window.__ModuleLoader__.load({
2935
2972
  onDisconnect: props.onDisconnectHost,
2936
2973
  onReconnect: props.onReconnectHost,
2937
2974
  onRestart: props.onRestartHost,
2938
- onStopRemote: requestStop,
2975
+ onStopRemote: props.onStopRemote,
2939
2976
  onEdit: props.onEditHost,
2940
2977
  onDelete: props.onDeleteHost,
2941
2978
  onDiagnose: props.onDiagnoseHost,
@@ -2947,15 +2984,7 @@ window.__ModuleLoader__.load({
2947
2984
  h(StatusDot, { status: connected > 0 ? 'connected' : 'idle' }),
2948
2985
  h('span', null, t('summary', { connected, total: hosts.length })),
2949
2986
  )
2950
- const stopDialog = h(StopRemoteDialog, {
2951
- key: 'stop-remote:' + (pendingStop ? pendingStop.id : ''),
2952
- t,
2953
- busy: stopBusy,
2954
- onConfirm: confirmStop,
2955
- onCancel: () => !stopBusy && setPendingStop(null),
2956
- })
2957
- const stopDialogNode = pendingStop !== null ? stopDialog : null
2958
- const body = box('div', 'drg-host-body', summary, visibleHosts.length > 0 ? list : null, stopDialogNode)
2987
+ const body = box('div', 'drg-host-body', summary, visibleHosts.length > 0 ? list : null)
2959
2988
  const retryProps = {
2960
2989
  variant: 'secondary',
2961
2990
  testId: 'live-reconnect',
@@ -4798,6 +4827,95 @@ window.__ModuleLoader__.load({
4798
4827
  return null
4799
4828
  }
4800
4829
  }
4830
+ const REMOTE_TITLE_POLL_MS = 1e3
4831
+ let localTitleBeforeRemote = null
4832
+ let titleBridgeEntry = null
4833
+ function documentTitleOf(win) {
4834
+ try {
4835
+ const title = win && win.document ? win.document.title : ''
4836
+ return typeof title === 'string' ? title.trim() : ''
4837
+ } catch (_error) {
4838
+ return ''
4839
+ }
4840
+ }
4841
+ function rememberLocalTitle() {
4842
+ if (localTitleBeforeRemote !== null || typeof document === 'undefined') return
4843
+ localTitleBeforeRemote = typeof document.title === 'string' ? document.title : ''
4844
+ }
4845
+ function restoreLocalTitle() {
4846
+ const saved = localTitleBeforeRemote
4847
+ localTitleBeforeRemote = null
4848
+ if (saved === null || saved === '' || typeof document === 'undefined' || document.title === saved) return
4849
+ document.title = saved
4850
+ }
4851
+ function syncRemoteTitle(entry) {
4852
+ if (entry === null || entry === void 0 || carrierPool.current !== entry.hostId) return
4853
+ const title = documentTitleOf(webWindow(entry))
4854
+ if (title === '' || typeof document === 'undefined' || document.title === title) return
4855
+ document.title = title
4856
+ }
4857
+ function attachTitleObserver(entry) {
4858
+ const win = webWindow(entry)
4859
+ if (win === null) return
4860
+ let node = null
4861
+ try {
4862
+ node = win.document.querySelector('title')
4863
+ } catch (_error) {
4864
+ return
4865
+ }
4866
+ if (!node || entry.titleNode === node) return
4867
+ try {
4868
+ if (entry.titleObserver) entry.titleObserver.disconnect()
4869
+ } catch (_error) {}
4870
+ entry.titleNode = node
4871
+ if (typeof MutationObserver !== 'function') return
4872
+ try {
4873
+ const observer = new MutationObserver(() => syncRemoteTitle(entry))
4874
+ observer.observe(node, { childList: true, subtree: true, characterData: true })
4875
+ entry.titleObserver = observer
4876
+ } catch (_error) {}
4877
+ }
4878
+ function attachParentTitleGuard(entry) {
4879
+ entry.parentTitleObserver?.disconnect()
4880
+ if (typeof MutationObserver !== 'function' || typeof document === 'undefined' || !document.head) return
4881
+ try {
4882
+ const observer = new MutationObserver(() => syncRemoteTitle(entry))
4883
+ observer.observe(document.head, { childList: true, subtree: true, characterData: true })
4884
+ entry.parentTitleObserver = observer
4885
+ } catch (_error) {}
4886
+ }
4887
+ function stopTitleBridge(entry) {
4888
+ if (entry === null || entry === void 0) return
4889
+ try {
4890
+ entry.titleObserver?.disconnect()
4891
+ entry.parentTitleObserver?.disconnect()
4892
+ } catch (_error) {}
4893
+ if (entry.titlePollTimer !== null && entry.titlePollTimer !== void 0 && typeof clearInterval === 'function') {
4894
+ clearInterval(entry.titlePollTimer)
4895
+ }
4896
+ entry.titleObserver = null
4897
+ entry.parentTitleObserver = null
4898
+ entry.titlePollTimer = null
4899
+ entry.titleNode = null
4900
+ if (titleBridgeEntry === entry) titleBridgeEntry = null
4901
+ }
4902
+ function startTitleBridge(entry) {
4903
+ if (entry === null || entry === void 0 || entry.kind !== 'web') return
4904
+ if (carrierPool.current !== entry.hostId) return
4905
+ if (titleBridgeEntry !== null && titleBridgeEntry !== entry) stopTitleBridge(titleBridgeEntry)
4906
+ rememberLocalTitle()
4907
+ titleBridgeEntry = entry
4908
+ attachTitleObserver(entry)
4909
+ attachParentTitleGuard(entry)
4910
+ if (entry.titlePollTimer === null || entry.titlePollTimer === void 0) {
4911
+ entry.titlePollTimer = setInterval(() => {
4912
+ attachTitleObserver(entry)
4913
+ syncRemoteTitle(entry)
4914
+ }, REMOTE_TITLE_POLL_MS)
4915
+ unrefTimer(entry.titlePollTimer)
4916
+ }
4917
+ syncRemoteTitle(entry)
4918
+ }
4801
4919
  function onWebFrameLoad(entry) {
4802
4920
  if (entry === null || entry.kind !== 'web') return
4803
4921
  const win = webWindow(entry)
@@ -4825,6 +4943,7 @@ window.__ModuleLoader__.load({
4825
4943
  }
4826
4944
  hideCarrierError(entry.errorLayer)
4827
4945
  markCarrierReady(entry)
4946
+ startTitleBridge(entry)
4828
4947
  const installed = installWebCarrier(entry, win)
4829
4948
  if (!installed) scheduleCarrierInstall(entry)
4830
4949
  if (carrierPool.current === entry.hostId) pushGuestHostRow()
@@ -5004,6 +5123,7 @@ window.__ModuleLoader__.load({
5004
5123
  }
5005
5124
  function disposeWebCarrier(entry) {
5006
5125
  stopCarrierInstall(entry)
5126
+ stopTitleBridge(entry)
5007
5127
  if (entry.loadGuard) entry.loadGuard.dispose()
5008
5128
  try {
5009
5129
  entry.frame.src = 'about:blank'
@@ -5088,10 +5208,15 @@ window.__ModuleLoader__.load({
5088
5208
  entry.view.reload()
5089
5209
  } catch (_error) {}
5090
5210
  }
5091
- for (const other of carrierPool.entries) if (other !== entry) other.root.style.display = 'none'
5211
+ for (const other of carrierPool.entries) {
5212
+ if (other === entry) continue
5213
+ other.root.style.display = 'none'
5214
+ if (other.kind === 'web') stopTitleBridge(other)
5215
+ }
5092
5216
  carrierPool.entries = [entry, ...carrierPool.entries.filter((item) => item !== entry)]
5093
5217
  const alreadyShown = carrierPool.current === hostId && entry.root.style.display !== 'none'
5094
5218
  carrierPool.current = hostId
5219
+ if (entry.kind === 'web') startTitleBridge(entry)
5095
5220
  if (alreadyShown) {
5096
5221
  entry.root.style.pointerEvents = ''
5097
5222
  entry.root.style.opacity = ''
@@ -5110,8 +5235,12 @@ window.__ModuleLoader__.load({
5110
5235
  carrierPool.wanted = null
5111
5236
  if (carrierPool.current === null) return
5112
5237
  stopHostRowPoll()
5113
- for (const entry of carrierPool.entries) entry.root.style.display = 'none'
5238
+ for (const entry of carrierPool.entries) {
5239
+ entry.root.style.display = 'none'
5240
+ if (entry.kind === 'web') stopTitleBridge(entry)
5241
+ }
5114
5242
  carrierPool.current = null
5243
+ restoreLocalTitle()
5115
5244
  ownCaptionBand(null, false)
5116
5245
  }
5117
5246
  let onCarrierDisposed = null
@@ -5125,6 +5254,8 @@ window.__ModuleLoader__.load({
5125
5254
  carrierPool.current = null
5126
5255
  ownCaptionBand(null, false)
5127
5256
  }
5257
+ if (entry.kind === 'web') stopTitleBridge(entry)
5258
+ if (wasShown) restoreLocalTitle()
5128
5259
  await entry.backend.dispose(entry)
5129
5260
  if (typeof onCarrierDisposed === 'function') onCarrierDisposed(entry.hostId)
5130
5261
  if (wasShown) updateSwitcher({ current: 'local' })
@@ -5146,6 +5277,8 @@ window.__ModuleLoader__.load({
5146
5277
  async function closeOverlay() {
5147
5278
  stopHostRowPoll()
5148
5279
  const hosts = carrierPool.entries.map((entry) => entry.hostId)
5280
+ for (const entry of carrierPool.entries) if (entry.kind === 'web') stopTitleBridge(entry)
5281
+ restoreLocalTitle()
5149
5282
  carrierPool.current = null
5150
5283
  ownCaptionBand(null, false)
5151
5284
  if (captionStateWatcher !== null) {
@@ -6511,6 +6644,35 @@ window.__ModuleLoader__.load({
6511
6644
  function ManageWindow(props) {
6512
6645
  const t = translatorOf(props)
6513
6646
  const locale = localeOf(props)
6647
+ const [pendingAction, setPendingAction] = useState(null)
6648
+ const [actionBusy, setActionBusy] = useState(false)
6649
+ const askHostAction = (kind, host2) => {
6650
+ if (!host2 || typeof host2.id !== 'string') return
6651
+ setPendingAction({ kind, host: host2 })
6652
+ }
6653
+ const cancelHostAction = () => {
6654
+ if (!actionBusy) setPendingAction(null)
6655
+ }
6656
+ const confirmHostAction = () => {
6657
+ const pending = pendingAction
6658
+ if (!pending || actionBusy) return
6659
+ const callback =
6660
+ pending.kind === 'stop'
6661
+ ? props.onStopRemoteHost
6662
+ : pending.kind === 'restart'
6663
+ ? props.onRestartHost
6664
+ : props.onDisconnectHost
6665
+ setActionBusy(true)
6666
+ const settle = () => {
6667
+ setActionBusy(false)
6668
+ setPendingAction(null)
6669
+ }
6670
+ try {
6671
+ Promise.resolve(typeof callback === 'function' ? callback(pending.host) : null).then(settle, settle)
6672
+ } catch (_error) {
6673
+ settle()
6674
+ }
6675
+ }
6514
6676
  if (props.open !== true) return null
6515
6677
  const host = props.host || null
6516
6678
  const connecting = props.view === 'connect' && host !== null && statusOf(host.status).window === true
@@ -6520,7 +6682,7 @@ window.__ModuleLoader__.load({
6520
6682
  h(
6521
6683
  Modal,
6522
6684
  { wide: true, onClose: props.onClose, closeLabel: t('cancel'), ariaLabel: t('hostsTitle') },
6523
- // The host list reads a subset under its own names; only `onStopRemote` is renamed, so the rest pass through.
6685
+ // The host list reads a subset under its own names: the three destructive actions ask here, before they run.
6524
6686
  connecting
6525
6687
  ? h(ConnectWindow, {
6526
6688
  t,
@@ -6533,8 +6695,24 @@ window.__ModuleLoader__.load({
6533
6695
  onRetry: () => props.onRetry(host),
6534
6696
  onDiagnose: () => props.onDiagnose(host),
6535
6697
  })
6536
- : h(HostListView, { ...props, onStopRemote: props.onStopRemoteHost }),
6698
+ : h(HostListView, {
6699
+ ...props,
6700
+ onDisconnectHost: (target) => askHostAction('disconnect', target),
6701
+ onRestartHost: (target) => askHostAction('restart', target),
6702
+ onStopRemote: (target) => askHostAction('stop', target),
6703
+ }),
6537
6704
  ),
6705
+ pendingAction
6706
+ ? h(HostActionDialog, {
6707
+ key: pendingAction.kind + ':' + pendingAction.host.id,
6708
+ t,
6709
+ kind: pendingAction.kind,
6710
+ hostName: String(pendingAction.host.name || pendingAction.host.id),
6711
+ busy: actionBusy,
6712
+ onConfirm: confirmHostAction,
6713
+ onCancel: cancelHostAction,
6714
+ })
6715
+ : null,
6538
6716
  )
6539
6717
  }
6540
6718
  function createOverlayActions(deps) {
@@ -7502,6 +7680,7 @@ window.__ModuleLoader__.load({
7502
7680
  { RemoteIcon, PluginOverlay, HostListView, HostCard, EmptyHosts },
7503
7681
  { ManageWindow, ConnectWindow, ConnectLog, ConnectProgress, ErrorCard },
7504
7682
  { FingerprintCard, PasswordPrompt, RemoteConflictPrompt, StopRemoteDialog, KeyFilePicker },
7683
+ { HostActionDialog },
7505
7684
  { WizardDialog, DiagnoseDrawer, SettingsModal, DownloadCenter, DownloadProgress },
7506
7685
  { StatusDot, Modal, Button, Notice, Toast },
7507
7686
  )
@@ -1,6 +1,7 @@
1
1
  /** Remote runtime preparation: `npx` pinned to the local DSH version against the remote's real `$DSH_HOME`; the
2
2
  * executor runs only fixed templates. */
3
3
  import { errors } from './errors.js';
4
+ import { REMOTE_OWNED_ENV } from './constants.js';
4
5
  import { headTail, shellQuote } from './util.js';
5
6
  import { isNodeVersionSupported, normalizeVersion, parseVersion, versionsEqual } from './version.js';
6
7
  export function assertSupportedRemote(facts) {
@@ -58,7 +59,7 @@ export function planNpx(input) {
58
59
  export function buildPreflightCommand(plan) {
59
60
  const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : '';
60
61
  return `set -eu
61
- ${pathPrefix}npm_config_loglevel=http ${shellQuote(plan.start.npxPath)} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} --version`;
62
+ ${pathPrefix}npm_config_loglevel=http ${REMOTE_OWNED_ENV}=1 ${shellQuote(plan.start.npxPath)} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} --version`;
62
63
  }
63
64
  export async function verifyNpxVersion(ssh, plan, options = {}) {
64
65
  const timeoutMs = options.timeoutMs ?? 0;
@@ -283,6 +283,7 @@ async function connectPipeline(ctx, runtime) {
283
283
  profile,
284
284
  timeoutMs: REMOTE_START_TIMEOUT_MS,
285
285
  onLine: (line) => log('debug', `remote: ${line}`),
286
+ onNotice: (line) => log('warn', line),
286
287
  });
287
288
  log('info', `remote DSH started: pid ${webInfo.pid ?? '?'}, port ${webInfo.port}`);
288
289
  }
@@ -6,7 +6,10 @@ export const API_PREFIX = '/dsh-remote-go/api';
6
6
  export const REMOTE_VIEW_PREFIX = '/dsh-remote-go/remote/';
7
7
  export const API_HEADER = 'x-dsh-remote-go';
8
8
  export const PLUGIN_ID = 'dsh-remote-go';
9
- export const PLUGIN_VERSION = '0.3.2';
9
+ /** Environment marker every DSH process this plugin launches carries, so the foreign-process scan can tell the
10
+ * plugin's own npx launch apart from a manual `dsh` (issue #97). It is inherited through npx into the final node. */
11
+ export const REMOTE_OWNED_ENV = 'DSH_REMOTE_GO_OWNED';
12
+ export const PLUGIN_VERSION = '0.3.3';
10
13
  export const MIN_DSH_VERSION = '0.2.2-rc.3';
11
14
  export const API_VERSION = '2.12';
12
15
  export const DEFAULT_KEY_PATH = '~/.ssh/id_rsa';
@@ -175,14 +175,54 @@ export const errors = {
175
175
  remoteDshMissing: plain('remote-dsh-missing'),
176
176
  nodeInstallFailed: plain('remote-node-install-failed'),
177
177
  remoteDshRunning: plain('remote-dsh-running'),
178
- remoteDshStartFailed: (tail) => fail('remote-dsh-start-failed', say('远端 DSH 进程没有成功打印 Web 地址,可能启动即失败。', 'The remote DSH process did not print its Web URL; startup likely failed.'), [
179
- ['查看诊断里的远端日志尾部', 'Inspect the remote log tail in diagnostics'],
180
- ['确认远端磁盘空间与端口可用', 'Check remote disk space and usable ports'],
181
- [
178
+ remoteDshStartFailed: (tail, details = {}) => {
179
+ const phase = details.phase ?? 'unknown';
180
+ const npm = details.npm ?? { status: 'unknown' };
181
+ const summary = phase === 'exited'
182
+ ? say('远端 DSH 进程启动后立即退出,没有打印 Web 地址。', 'The remote DSH process exited right after launch without printing its Web URL.')
183
+ : phase === 'timeout'
184
+ ? say('远端 DSH 进程在等待时间内没有打印 Web 地址。', 'The remote DSH process did not print its Web URL within the wait window.')
185
+ : phase === 'unparseable'
186
+ ? say('远端 DSH 进程已经启动,但没有打印可识别的 Web 地址。', 'The remote DSH process started but never printed a recognizable Web URL.')
187
+ : say('远端 DSH 没有成功打印 Web 地址,启动过程中断。', 'The remote DSH did not print its Web URL; the launch did not complete.');
188
+ const steps = [];
189
+ steps.push(['查看下方的启动输出与远端日志尾部', 'Read the launch output and remote log tail below']);
190
+ if (npm.status === 'unwritable') {
191
+ steps.push([
192
+ `远端 ~/.npm/_logs 不可写,npm 无法创建调试日志;检查该目录的权限与空间`,
193
+ 'The remote ~/.npm/_logs is not writable, so npm could not create a debug log; check its permissions and free space',
194
+ ]);
195
+ }
196
+ else if (npm.status === 'found') {
197
+ steps.push([
198
+ 'npm 调试日志已附在技术详情末尾,先看其中的 error 行',
199
+ 'The newest npm debug log is appended to the technical details; read its error lines first',
200
+ ]);
201
+ }
202
+ else {
203
+ steps.push(['核对远端磁盘空间、端口与 npm 可用性', 'Check remote disk space, usable ports and npm availability']);
204
+ }
205
+ steps.push([
182
206
  '重试一次,若仍失败可手动在远端验证 `dsh --profile web --no-open`',
183
207
  'Retry, or verify `dsh --profile web --no-open` manually on the remote host',
184
- ],
185
- ], { technical: tail }),
208
+ ]);
209
+ // The technical block starts with the launch tail, then appends the npm debug log the panel used to leave on the
210
+ // remote. The phase lives in the visible detail, so this section stays valid raw process output line by line.
211
+ const sections = [tail];
212
+ if (npm.status === 'found') {
213
+ sections.push(`--- npm log ${npm.path ?? '~/.npm/_logs'} ---`, npm.tail ?? '(empty)');
214
+ }
215
+ else if (npm.status === 'unwritable') {
216
+ sections.push('--- npm log ---', '~/.npm/_logs is not writable; npm could not create a debug log');
217
+ }
218
+ else if (npm.status === 'missing') {
219
+ sections.push('--- npm log ---', '~/.npm/_logs does not exist; npm wrote no debug log');
220
+ }
221
+ else if (npm.status === 'empty') {
222
+ sections.push('--- npm log ---', '~/.npm/_logs has no *-debug-0.log file');
223
+ }
224
+ return fail('remote-dsh-start-failed', summary, steps, { technical: sections.join('\n') });
225
+ },
186
226
  remoteUiUnreachable: plain('remote-ui-unreachable'),
187
227
  // Kept apart from `remote-ui-unreachable`: here the tunnel may be fine and the process is what is
188
228
  // missing, which is what the restart button exists for.
@@ -1,6 +1,6 @@
1
1
  /** Remote process and reachability primitives: find, stop and probe DSH processes on the remote, plus the one HTTP round-trip that proves the remote UI answers. */
2
2
  import http from 'node:http';
3
- import { TUNNEL_PROBE_TIMEOUT_MS } from './constants.js';
3
+ import { REMOTE_OWNED_ENV, TUNNEL_PROBE_TIMEOUT_MS } from './constants.js';
4
4
  import { isPid, messageOf } from './util.js';
5
5
  /** A listener answering 200, 302 or 401 is up: 401 without the launch cookie still proves it serves. */
6
6
  export function isUiUp(status) {
@@ -24,7 +24,13 @@ printf '%s\\n' "$PS_OUT" | while IFS= read -r LINE; do
24
24
  case "$COMM" in node|dsh|npm|npx) ;; *) continue ;; esac
25
25
  case "$ARGS" in *"@deepseek-ai/dsh"*|*"/bin/dsh "*|*" dsh "*) ;; *) continue ;; esac
26
26
  case "$ARGS" in *"ps -eww"*|*"PS_OUT"*|*"IGNORE"*) continue ;; esac
27
- ENV_HOME=$(tr '\\0' '\\n' < "/proc/$PID/environ" 2>/dev/null | sed -n 's/^DSH_HOME=//p' | tail -n 1)
27
+ ENV_TEXT=$(tr '\\0' '\\n' < "/proc/$PID/environ" 2>/dev/null || true)
28
+ # Every npx launch this plugin performs carries REMOTE_OWNED_ENV, and the marker survives npx into the final node
29
+ # process. Matching it is the identity check the scan was missing: the plugin's own launch has the same argv and the
30
+ # same DSH_HOME as a manual DSH, and its pid is only knowable after the registry lands.
31
+ OWNED=$(printf '%s\\n' "$ENV_TEXT" | sed -n 's/^${REMOTE_OWNED_ENV}=//p' | tail -n 1)
32
+ [ -n "\${OWNED:-}" ] && continue
33
+ ENV_HOME=$(printf '%s\\n' "$ENV_TEXT" | sed -n 's/^DSH_HOME=//p' | tail -n 1)
28
34
  if [ -n "\${ENV_HOME:-}" ] && [ "$ENV_HOME" != "$HOME/.dsh" ]; then continue; fi
29
35
  printf '%s\\t%s\\n' "$PID" "$ARGS"
30
36
  done`;
@@ -1,4 +1,4 @@
1
- import { DEFAULT_REMOTE_PROFILE, REMOTE_START_TIMEOUT_MS } from '../constants.js';
1
+ import { DEFAULT_REMOTE_PROFILE, REMOTE_OWNED_ENV, REMOTE_START_TIMEOUT_MS } from '../constants.js';
2
2
  import { errors } from '../errors.js';
3
3
  import { remoteLayout } from '../layout.js';
4
4
  import { headTail, isLoopbackHost, isPid, messageOf, shellQuote } from '../util.js';
@@ -17,19 +17,23 @@ export function buildStartCommand(plan, layout, options = {}) {
17
17
  const patch = options.patchPath ? `--patch ${shellQuote(options.patchPath)} ` : '';
18
18
  const args = `${patch}--profile ${shellQuote(profile)} --no-open --port 0`;
19
19
  const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : '';
20
- return `env DSH_HOME=${shellQuote(layout.dshHome)} ${pathPrefix}${shellQuote(plan.start.npxPath ?? 'npx')} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} ${args}`;
20
+ return `env DSH_HOME=${shellQuote(layout.dshHome)} ${REMOTE_OWNED_ENV}=1 ${pathPrefix}${shellQuote(plan.start.npxPath ?? 'npx')} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} ${args}`;
21
21
  }
22
22
  export function buildBrowserCarrierProbe(plan, layout, profile) {
23
23
  const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : '';
24
24
  const dumpFile = shellQuote(`${layout.root}/profile-dump.yml`);
25
+ const errorFile = shellQuote(`${layout.root}/profile-dump.err`);
25
26
  const patchFile = shellQuote(`${layout.root}/${BROWSER_CARRIER_PATCH_FILE}`);
26
27
  return `set -u
27
28
  umask 077
28
29
  mkdir -p ${shellQuote(layout.root)}
29
30
  DUMP=${dumpFile}
30
- if ! env DSH_HOME=${shellQuote(layout.dshHome)} ${pathPrefix}${shellQuote(plan.start.npxPath ?? 'npx')} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} --profile ${shellQuote(profile)} --dump-config > "$DUMP" 2>/dev/null; then
31
+ DUMP_ERR=${errorFile}
32
+ if ! env DSH_HOME=${shellQuote(layout.dshHome)} ${REMOTE_OWNED_ENV}=1 ${pathPrefix}${shellQuote(plan.start.npxPath ?? 'npx')} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} --profile ${shellQuote(profile)} --dump-config > "$DUMP" 2>"$DUMP_ERR"; then
31
33
  echo "DUMP-FAILED"
32
- rm -f "$DUMP"
34
+ # The probe failure used to be a debug line with no reason: hand its stderr back so the warning names it (#96).
35
+ tail -n 20 "$DUMP_ERR" 2>/dev/null || true
36
+ rm -f "$DUMP" "$DUMP_ERR"
33
37
  exit 0
34
38
  fi
35
39
  if grep -A6 'id: api-remotes' "$DUMP" | grep -q 'disabled: true'; then
@@ -40,7 +44,7 @@ DSH_REMOTE_GO_PATCH
40
44
  else
41
45
  echo "CLEAR"
42
46
  fi
43
- rm -f "$DUMP"`;
47
+ rm -f "$DUMP" "$DUMP_ERR"`;
44
48
  }
45
49
  export async function ensureBrowserCarrier(ssh, options) {
46
50
  try {
@@ -56,12 +60,12 @@ export async function ensureBrowserCarrier(ssh, options) {
56
60
  options.onLine?.('browser carrier: api-remotes is enabled by the profile');
57
61
  return { status: 'clear', patchPath: null };
58
62
  }
59
- options.onLine?.(`browser carrier: profile probe failed (${headTail(result.stdout + result.stderr, 300)})`);
63
+ options.onNotice?.(`browser carrier: profile probe failed (${headTail(result.stdout + result.stderr, 300)})`);
60
64
  return { status: 'unknown', patchPath: null };
61
65
  }
62
66
  catch (error) {
63
67
  // swallow-ok: launching without the overlay keeps the start error (missing profile, npx failure)
64
- options.onLine?.(`browser carrier: probe failed (${messageOf(error)})`);
68
+ options.onNotice?.(`browser carrier: probe failed (${messageOf(error)})`);
65
69
  return { status: 'unknown', patchPath: null };
66
70
  }
67
71
  }
@@ -121,10 +125,76 @@ export function parseLaunchedPid(text) {
121
125
  const started = /(?:^|\n)PID:(\d+)\s*(?:\n|$)/.exec(combined);
122
126
  return started ? { pid: Number(started[1]), port: 0 } : { pid: 0, port: 0 };
123
127
  }
128
+ /** The newest remote npm debug log, or the one reason it cannot be read. Never throws: a diagnostic read failing must
129
+ * not replace the start failure that asked for it. */
130
+ export async function readRemoteNpmLogDiagnostics(ssh, options = {}) {
131
+ try {
132
+ const result = await ssh.exec(buildNpmLogProbeCommand(), {
133
+ timeoutMs: options.timeoutMs ?? 8_000,
134
+ maxBytes: 64_000,
135
+ });
136
+ if (result.code !== 0)
137
+ return { status: 'unknown' };
138
+ return parseNpmLogProbe(result.stdout);
139
+ }
140
+ catch {
141
+ // swallow-ok: the npm log is best-effort evidence; the start error still carries its launch output
142
+ return { status: 'unknown' };
143
+ }
144
+ }
145
+ /** The remote-side probe: prove whether `~/.npm/_logs` is writable, then hand back the newest debug log's tail. */
146
+ export function buildNpmLogProbeCommand() {
147
+ return `set -u
148
+ LOG_DIR="$HOME/.npm/_logs"
149
+ if [ ! -d "$LOG_DIR" ]; then echo "NPM-LOGS:missing"; exit 0; fi
150
+ PROBE="$LOG_DIR/.dsh-remote-go-probe.$$"
151
+ if ! (: > "$PROBE") 2>/dev/null; then echo "NPM-LOGS:unwritable"; exit 0; fi
152
+ rm -f "$PROBE" 2>/dev/null || true
153
+ LATEST=$(ls -1t "$LOG_DIR"/*-debug-0.log 2>/dev/null | head -n 1)
154
+ if [ -z "$LATEST" ]; then echo "NPM-LOGS:empty"; exit 0; fi
155
+ echo "NPM-LOGS:found"
156
+ echo "NPM-PATH:$LATEST"
157
+ tail -n 40 "$LATEST" 2>/dev/null || true`;
158
+ }
159
+ export function parseNpmLogProbe(stdout) {
160
+ const text = String(stdout ?? '');
161
+ const status = /^NPM-LOGS:(missing|empty|unwritable|found)$/m.exec(text)?.[1];
162
+ if (status === undefined)
163
+ return { status: 'unknown' };
164
+ if (status !== 'found')
165
+ return { status: status };
166
+ const result = { status: 'found' };
167
+ const path = /^NPM-PATH:(.+)$/m.exec(text)?.[1]?.trim();
168
+ if (path)
169
+ result.path = path;
170
+ const bodyStart = text.search(/^NPM-PATH:.*$/m);
171
+ const body = bodyStart < 0 ? '' : text.slice(text.indexOf('\n', bodyStart) + 1).trim();
172
+ const tail = headTail(body, 4_000).trim();
173
+ if (tail !== '')
174
+ result.tail = tail;
175
+ return result;
176
+ }
177
+ /** Which failure the launch script proved: it exited, it waited out the window, or it started without a usable URL. */
178
+ export function startFailurePhase(text, code) {
179
+ const value = String(text ?? '');
180
+ if (/(?:^|\n)EXITED:\d+/.test(value) || code === 3)
181
+ return 'exited';
182
+ if (/(?:^|\n)TIMEOUT(?:\n|$)/.test(value) || code === 4)
183
+ return 'timeout';
184
+ if (code === 0 || /(?:^|\n)(?:DONE|LINE):/.test(value))
185
+ return 'unparseable';
186
+ return 'unknown';
187
+ }
124
188
  export async function startRemoteWeb(ssh, options) {
125
189
  const layout = options.layout ?? remoteLayout(options.home);
126
190
  const profile = options.profile ?? options.plan.profile ?? DEFAULT_REMOTE_PROFILE;
127
- const carrier = await ensureBrowserCarrier(ssh, { plan: options.plan, layout, profile, onLine: options.onLine });
191
+ const carrier = await ensureBrowserCarrier(ssh, {
192
+ plan: options.plan,
193
+ layout,
194
+ profile,
195
+ onLine: options.onLine,
196
+ onNotice: options.onNotice,
197
+ });
128
198
  const startCommand = buildStartCommand(options.plan, layout, { profile, patchPath: carrier.patchPath });
129
199
  const script = buildStartScript(startCommand, layout, {
130
200
  waitSeconds: Math.ceil((options.timeoutMs ?? REMOTE_START_TIMEOUT_MS) / 1000),
@@ -147,28 +217,38 @@ export async function startRemoteWeb(ssh, options) {
147
217
  // The launch script prints its pid before it waits, so a failure can still stop what it started.
148
218
  const combined = `${result.stdout}\n${result.stderr}`;
149
219
  const launched = parseLaunchedPid(combined);
150
- const failed = async (error) => {
151
- if (isPid(launched.pid)) {
152
- let alive = false;
153
- try {
154
- alive = await remotePidAlive(ssh, launched.pid);
155
- }
156
- catch {
157
- // swallow-ok: an unreadable liveness check means "cannot prove it is ours", so no signal
158
- }
159
- if (alive) {
160
- const stopped = await stopRemoteWeb(ssh, layout, { pid: launched.pid });
161
- const outcome = stopped.ok === true ? 'it was stopped' : 'it could not be stopped';
162
- options.onLine?.(`start failed after pid ${launched.pid} was launched; ${outcome}`);
163
- }
220
+ /** Stop what this launch started before its error surfaces: a failed start must not leave an orphan behind. */
221
+ const stopLaunched = async () => {
222
+ if (!isPid(launched.pid))
223
+ return;
224
+ let alive = false;
225
+ try {
226
+ alive = await remotePidAlive(ssh, launched.pid);
164
227
  }
228
+ catch {
229
+ // swallow-ok: an unreadable liveness check means "cannot prove it is ours", so no signal
230
+ }
231
+ if (alive) {
232
+ const stopped = await stopRemoteWeb(ssh, layout, { pid: launched.pid });
233
+ const outcome = stopped.ok === true ? 'it was stopped' : 'it could not be stopped';
234
+ options.onLine?.(`start failed after pid ${launched.pid} was launched; ${outcome}`);
235
+ }
236
+ };
237
+ const failed = async (error) => {
238
+ await stopLaunched();
165
239
  return error;
166
240
  };
241
+ /** A start failure: stop the pid, then read the npm debug log so the panel carries the real cause (issue #96). */
242
+ const failStart = async (phase) => {
243
+ await stopLaunched();
244
+ const npm = await readRemoteNpmLogDiagnostics(ssh);
245
+ return errors.remoteDshStartFailed(headTail(combined, 1500), { phase, npm });
246
+ };
167
247
  if (result.code !== 0)
168
- throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)));
248
+ throw await failStart(startFailurePhase(combined, result.code));
169
249
  const parsed = parseWebLine(combined);
170
250
  if (!parsed)
171
- throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)));
251
+ throw await failStart(startFailurePhase(combined, result.code));
172
252
  if (!isLoopbackHost(parsed.host)) {
173
253
  throw await failed(errors.remoteUiUnreachable({
174
254
  zh: `远端 DSH 宣布的地址不是回环地址(${parsed.host}),无法安全地经 SSH 隧道访问。`,
@@ -311,17 +311,19 @@ export function reportTool(options) {
311
311
  const id = input.id;
312
312
  const wanted = selectedParts(input.parts);
313
313
  // The two halves are read lazily, so a composition that mounts only one still answers its half: the missing
314
- // member is a structured UNSUPPORTED, never a TypeError.
315
- const diagnose = service.diagnose;
316
- const logView = service.logView;
317
- if (wanted.checks && typeof diagnose !== 'function')
314
+ // member is a structured UNSUPPORTED, never a TypeError. Both are bound to the service on purpose: they are
315
+ // prototype methods that read `this.ctx` / `this.init`, and a detached copy used to die with
316
+ // "Cannot read properties of undefined (reading 'init')" exactly when the host was not connected.
317
+ const diagnose = typeof service.diagnose === 'function' ? service.diagnose.bind(service) : null;
318
+ const logView = typeof service.logView === 'function' ? service.logView.bind(service) : null;
319
+ if (wanted.checks && diagnose === null)
318
320
  return { ok: false, error: unsupported('checks') };
319
- if (wanted.logs && typeof logView !== 'function')
321
+ if (wanted.logs && logView === null)
320
322
  return { ok: false, error: unsupported('logs') };
321
323
  await service.init?.();
322
324
  const result = { ok: true, host: hostRow(service, id) };
323
325
  let dropped = false;
324
- if (wanted.checks) {
326
+ if (wanted.checks && diagnose !== null) {
325
327
  // A thrown coded error is this half's unknown-host answer: `serviceError` keeps the code and the bilingual
326
328
  // reason, and the catch below logs it once.
327
329
  const report = await diagnose(id);
@@ -335,7 +337,7 @@ export function reportTool(options) {
335
337
  result.counts = checks.counts;
336
338
  dropped = checks.dropped;
337
339
  }
338
- if (wanted.logs) {
340
+ if (wanted.logs && logView !== null) {
339
341
  const view = logView(id);
340
342
  if (!view)
341
343
  return { ok: false, error: hostNotFound(id) };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-go",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "DSH 插件:在本地 DSH 里通过 SSH 使用远端 DSH(主机条切换、整窗接管、连接进度与日志、重启/关闭远端、远端文件下载、给本地 AI 会话的主机清单 / 体检报告 / 受控远端命令,三者默认隐藏按需解锁;插件自带 Node + npx,数据留在远端 ~/.dsh) | DSH plugin: use a remote DSH over SSH inside your local DSH (host switcher, full-window UI, connect progress and log, remote restart/stop, remote file downloads, and a host list / diagnosis report / guarded remote command for local AI sessions — hidden until the session unlocks them; plugin-managed Node + npx, data stays in the remote ~/.dsh)",
5
5
  "keywords": [
6
6
  "deepseek",