dsh-remote-plugin 0.7.6 → 0.8.0-rc.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/index.mjs CHANGED
@@ -209,7 +209,7 @@ async function proxyGateway(path, method, body) {
209
209
  'x-dsh-remote-client': 'admin',
210
210
  },
211
211
  body: method === 'POST' ? body : undefined,
212
- signal: AbortSignal.timeout(path.startsWith('/admin/api/dsh') ? 15000 : 5000),
212
+ signal: AbortSignal.timeout(path === '/admin/api/relay' ? 18000 : path.startsWith('/admin/api/dsh') ? 15000 : 5000),
213
213
  })
214
214
  const json = await res.json().catch(() => ({ ok: false, error: `gateway ${res.status}` }))
215
215
  return { status: res.status, json }
@@ -414,6 +414,11 @@ async function startGateway() {
414
414
 
415
415
  // 无 systemd 的机器回退: detached 子进程
416
416
  if (!sysd) {
417
+ // Windows locks a process's current directory. Keep both supervisor and
418
+ // worker outside the replaceable node_modules package during self-update.
419
+ const gatewayCwd = `${homedir()}/.dsh-remote`
420
+ try { mkdirSync(gatewayCwd, { recursive: true }) }
421
+ catch { return { ok: false, running: false, error: '无法创建网关运行目录,请检查用户目录权限' } }
417
422
  let logFd = null
418
423
  try {
419
424
  logFd = openSync(`${homedir()}/.dsh-remote/plugin-gateway.log`, 'a')
@@ -422,7 +427,7 @@ async function startGateway() {
422
427
  delete gatewayEnv.NODE_CHANNEL_FD
423
428
  delete gatewayEnv.NODE_CHANNEL_SERIALIZATION_MODE
424
429
  const child = spawn(process.execPath, [script, '--supervise'], {
425
- cwd: dirname(script),
430
+ cwd: gatewayCwd,
426
431
  detached: true,
427
432
  stdio: ['ignore', logFd ?? 'ignore', logFd ?? 'ignore'],
428
433
  env: gatewayEnv,
@@ -598,8 +603,11 @@ async function executeRegisteredCommand(ctx, agent, line, signal) {
598
603
 
599
604
  function beginCommandOperation(ctx, agent, sessionId, line, command) {
600
605
  const existing = commandOperations.get(sessionId)
601
- if (existing?.active) return { operation: existing, reused: true }
602
- const operation = { active: true, phase: 'running', command, startedAt: Date.now(), endedAt: 0, message: '' }
606
+ if (existing?.active) {
607
+ if (existing.line !== line) throw new Error('当前会话已有命令正在执行,请等待完成后再提交。')
608
+ return { operation: existing, reused: true }
609
+ }
610
+ const operation = { active: true, phase: 'running', command, line, startedAt: Date.now(), endedAt: 0, message: '' }
603
611
  commandOperations.set(sessionId, operation)
604
612
  // 不把已登记命令绑定到 HTTP 超时:真实 command/done 才是完成边界。
605
613
  // 处理器仍接收可用 AbortSignal,以符合命令执行器的契约。
@@ -793,6 +801,13 @@ async function serveStatic(req, res, ctx) {
793
801
  [`${MOUNT}/admin/api/device-keys/rotate`, '/device-keys/rotate'],
794
802
  [`${MOUNT}/admin/api/device-keys/revoke`, '/device-keys/revoke'],
795
803
  ])
804
+ if (pathname === `${MOUNT}/admin/api/relay`) {
805
+ if (!['GET', 'POST'].includes(req.method)) { res.writeHead(405, { allow: 'GET, POST' }); res.end(); return }
806
+ const body = req.method === 'POST' ? await readBody(req, 4096) : undefined
807
+ const proxied = await proxyGateway('/admin/api/relay', req.method, body)
808
+ sendJson(res, proxied?.status || 502, proxied?.json || { error: 'GATEWAY_UNAVAILABLE' })
809
+ return
810
+ }
796
811
  if (gatewayAdminMutations.has(pathname)) {
797
812
  if (req.method !== 'POST') {
798
813
  res.writeHead(405, { allow: 'POST' })
@@ -975,7 +990,7 @@ async function serveStatic(req, res, ctx) {
975
990
  }
976
991
  // /export 的成功结果必须先回到客户端,由客户端再发起 ZIP 下载;其他已登记
977
992
  // 命令统一异步受理,避免把未知耗时绑定到一条 HTTP 请求。
978
- if (name && name !== 'export') {
993
+ if (name && (name !== 'export' || body.async === true)) {
979
994
  const { operation, reused } = beginCommandOperation(ctx, agent, sessionId, line, name)
980
995
  sendJson(res, 202, {
981
996
  ok: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.7.6",
3
+ "version": "0.8.0-rc.3",
4
4
  "description": "DSH Remote 官方 bundle 插件:DSH 左侧原生边栏入口 + 右侧抽屉内嵌管理控制台;内置网关随 DSH 自动启停(systemd 独立单元),抽屉直显令牌与设备监控;网关提供 /fs/* 文件传输端点(列表/断点下载/上传),配合 Android App 远程操控会话/审批/提问/goal 与文件互传(多服务器测速切换、聊天记录离线缓存)。",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
package/plugin-center.mjs CHANGED
@@ -191,11 +191,15 @@ export function createPluginCenter(ctx, options = {}) {
191
191
  const probe = options.probeProcesses || probeProcesses
192
192
  const launch = options.launch || (args => {
193
193
  const desktop = profile?.cliMode === 'desktop'
194
+ // A self-update can replace this module's package directory. Run a private
195
+ // snapshot from the profile ledger, with an explicit stable working dir.
196
+ const workerFile = join(profile.dir, '.remote-plugin-center', 'worker-' + args[2] + '.mjs')
197
+ writeFileSync(workerFile, readFileSync(SELF), { flag: 'wx', mode: 0o600 })
194
198
  const errorLog = openSync(join(profile.dir, '.remote-plugin-center', 'worker-' + args[2] + '.log'), 'a', 0o600)
195
199
  let child
196
200
  try {
197
- child = spawn(process.execPath, [...(desktop ? ['--expose-internals'] : []), SELF, '--worker', ...args], {
198
- detached: true, windowsHide: true, stdio: ['ignore', 'ignore', errorLog],
201
+ child = spawn(process.execPath, [...(desktop ? ['--expose-internals'] : []), workerFile, '--worker', ...args], {
202
+ cwd: profile.dir, detached: true, windowsHide: true, stdio: ['ignore', 'ignore', errorLog],
199
203
  env: { ...process.env, ...(desktop ? { ELECTRON_RUN_AS_NODE: '1' } : {}) },
200
204
  })
201
205
  } finally { closeSync(errorLog) }
@@ -410,6 +414,9 @@ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node'
410
414
  job.message = '配置已保存;重启 DSH 后生效。安装脚本未执行。'
411
415
  } catch (error) {
412
416
  job.phase = 'failed'; job.message = String(error.message || error)
417
+ if(job.name==='dsh-remote-plugin' && /(?:ERR_PNPM_)?(?:EPERM|EBUSY)/.test(job.log) && /rename/i.test(job.log)) {
418
+ job.message = 'Windows 拒绝替换 Remote 插件目录,可能仍有旧网关或 DSH 进程占用。更新未完成,配置和旧包备份已保留;请退出对应 DSH Desktop 及其 Remote 网关后,使用同一 Desktop 安装自带的 CLI 在当前 profile 重装目标版本,再启动 DSH。不要删除插件目录或强行覆盖;不能假定失败后已自动回滚。'
419
+ }
413
420
  // A failed package manager may have changed files. Never claim rollback.
414
421
  job.restartRequired = true
415
422
  } finally {
@@ -0,0 +1,126 @@
1
+ /* Compact, shared conversation activity. Durable events remain untouched. */
2
+ 'use strict';
3
+ ;(function(root){
4
+ const esc=value=>String(value??'').replace(/[&<>"']/g,char=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[char]))
5
+ const text=(zh,en)=>root.I18N?.lang==='en'?en:zh
6
+ const json=value=>{try{return typeof value==='string'?value:JSON.stringify(value,null,2)??''}catch{return String(value)}}
7
+ const cut=(value,length)=>{const source=String(value??'');return source.length>length?source.slice(0,length)+'…':source}
8
+ const brief=value=>cut(String(value??'').replace(/\s+/g,' ').trim(),100)
9
+ const icon=kind=>`<svg class="activity-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${kind==='reasoning'?'m12 3 2.4 6.6L21 12l-6.6 2.4L12 21l-2.4-6.6L3 12l6.6-2.4Z':'m8 7-5 5 5 5m8-10 5 5-5 5m-3-14-2 18'}"/></svg>`
10
+ function argumentHint(value){
11
+ if(typeof value==='string'){try{value=JSON.parse(value)}catch{return brief(value)}}
12
+ if(!value||typeof value!=='object')return ''
13
+ for(const key of ['description','command','cmd','path','file_path','pattern','query','url','line'])if(typeof value[key]==='string')return brief(value[key])
14
+ return ''
15
+ }
16
+ function shell(kind,key,title,hint,state,body,live=false,error=false){
17
+ return `<details class="chat-activity activity-${kind}${live?' is-live':''}${error?' is-error':''}" data-activity-key="${esc(key)}"><summary>${icon(kind)}<span class="activity-copy"><span class="activity-title">${esc(title)}</span>${hint?`<span class="activity-hint">${esc(hint)}</span>`:''}</span><span class="activity-state">${live?'<i aria-hidden="true"></i>':''}${esc(state)}</span><span class="activity-chevron" aria-hidden="true"></span></summary><div class="activity-body">${body}</div></details>`
18
+ }
19
+ function reasoning(value={}){
20
+ const source=String(value.text??'')
21
+ const hint=brief(source.split('\n').filter(line=>line.trim()).at(-1)||'')
22
+ return shell('reasoning',value.key,text(value.live?'思考中':'思考过程',value.live?'Thinking':'Reasoning'),hint,value.live?text('进行中','Live'):'',`<div class="activity-reasoning-text">${esc(cut(source,12000))}</div>`,!!value.live)
23
+ }
24
+ const errorOf=data=>!!(data?.error||data?.ok===false||data?.isError===true)
25
+ function tool(value={}){
26
+ const args=value.args,returned=Object.hasOwn(value,'result'),error=!!value.error
27
+ const section=(title,content)=>`<section><h4>${esc(title)}</h4><pre>${esc(cut(json(content),12000))}</pre></section>`
28
+ const body=(args===undefined?'':section(text('参数','Arguments'),args))+(returned?section(text('结果','Result'),value.result):`<p class="activity-note">${esc(text('当前记录中尚无对应结果。','No matching result in the loaded history.'))}</p>`)
29
+ return shell('tool',value.key,value.name||text(returned?'工具结果':'工具调用',returned?'Tool result':'Tool call'),argumentHint(args),text(error?'返回错误':returned?'已返回':'已调用',error?'Error':returned?'Returned':'Called'),body,false,error)
30
+ }
31
+ const dataOf=entry=>entry.event?.data||{}
32
+ const callId=data=>data.callId||data.message?.source?.callId
33
+ const resultOf=data=>data.error??data.result??data.output??data.message??data.text??data.content??data
34
+ const pairs=new WeakMap()
35
+ function prepare(entries){
36
+ const pending=new Map(),matched=new Map(),consumed=new Set()
37
+ for(const entry of entries){
38
+ const data=dataOf(entry),id=callId(data)
39
+ if(!id)continue
40
+ if(entry.event?.type==='tool/call'){const queue=pending.get(id)||[];queue.push(entry);pending.set(id,queue)}
41
+ else if(entry.event?.type==='tool/result'){
42
+ const queue=pending.get(id)||[]
43
+ const index=queue.findLastIndex(call=>data.turn==null||dataOf(call).turn==null||data.turn===dataOf(call).turn)
44
+ if(index>=0){const [call]=queue.splice(index,1);matched.set(call,entry);consumed.add(entry)}
45
+ }
46
+ }
47
+ return entries.filter(entry=>!consumed.has(entry)).map(entry=>{
48
+ if(entry.event?.type!=='tool/call')return entry
49
+ const result=matched.get(entry)
50
+ if(!result)return entry
51
+ const cached=pairs.get(entry)
52
+ if(cached?.result===result)return cached.entry
53
+ const data=dataOf(entry),output=dataOf(result)
54
+ const next={...entry,view:{...entry.view,toolActivity:{key:'tool:'+entry.seq,name:data.name||data.toolName,args:data.arguments??data.args??data.input,result:resultOf(output),error:errorOf(output)}}}
55
+ pairs.set(entry,{result,entry:next});return next
56
+ })
57
+ }
58
+ function toolEvent(entry){
59
+ if(entry.view?.toolActivity)return tool(entry.view.toolActivity)
60
+ const data=dataOf(entry),isResult=entry.event?.type==='tool/result'
61
+ return tool({key:'tool:'+entry.seq,name:data.name||data.toolName||(isResult?text('工具结果','Tool result'):undefined),...(isResult?{result:resultOf(data),error:errorOf(data)}:{args:data.arguments??data.args??data.input})})
62
+ }
63
+ function reasoningKind(block){return block&&typeof block==='object'&&(block.type==='thinking'||block.type==='reasoning')}
64
+ function messageBlocks(entry){
65
+ const data=entry?.event?.data||{},message=data.message||{}
66
+ const blocks=Array.isArray(message.content)?message.content:(Array.isArray(data.content)?data.content:null)
67
+ return blocks?{data,message,blocks}:null
68
+ }
69
+ function stripReasoning(entry,rest){
70
+ const parts=messageBlocks(entry)
71
+ const data={...parts.data}
72
+ if(Array.isArray(parts.message.content))data.message={...parts.message,content:rest}
73
+ else data.content=rest
74
+ return {...entry,event:{...entry.event,data}}
75
+ }
76
+ /**
77
+ * Collapse a turn's process — every tool activity plus the reasoning blocks that would
78
+ * otherwise occupy a row inside each assistant message — into one disclosure.
79
+ * A user message starts a new turn; a turn without enough items keeps its original rows.
80
+ */
81
+ function group(entries){
82
+ const isTool=entry=>{const type=entry?.event?.type;return type==='tool/call'||type==='tool/result'}
83
+ // Only a human message starts a new turn; injected system-reminder user events do not.
84
+ const isTurnStart=entry=>{
85
+ if(entry?.event?.type!=='user/message')return false
86
+ const data=entry.event.data||{},source=data.source??data.message?.source
87
+ return !source||source.kind==='user'
88
+ }
89
+ const out=[]
90
+ const emit=segment=>{
91
+ const items=[],stripped=new Map()
92
+ for(const entry of segment){
93
+ if(isTool(entry)){items.push({kind:'tool',seq:entry.seq,entry});continue}
94
+ const parts=messageBlocks(entry)
95
+ if(!parts)continue
96
+ const reasoning=parts.blocks.filter(reasoningKind)
97
+ if(!reasoning.length)continue
98
+ const rest=parts.blocks.filter(block=>!reasoningKind(block))
99
+ const copy=stripReasoning(entry,rest)
100
+ stripped.set(entry,{copy,empty:rest.length===0})
101
+ reasoning.forEach((block,index)=>items.push({kind:'reasoning',seq:Number(entry.seq)+(index+1)/1000,text:String(block.text??block.content??''),key:'reasoning:'+entry.seq+':'+index}))
102
+ }
103
+ if(items.length>1){
104
+ let emitted=false
105
+ for(const entry of segment){
106
+ const decorated=stripped.get(entry)
107
+ if((isTool(entry)||decorated)&&!emitted){out.push({seq:items[0].seq,event:{type:'activity/group'},view:{activityGroup:{items}}});emitted=true}
108
+ if(isTool(entry))continue
109
+ if(decorated){if(!decorated.empty)out.push(decorated.copy);continue}
110
+ out.push(entry)
111
+ }
112
+ }else out.push(...segment)
113
+ }
114
+ let segment=[]
115
+ for(const entry of entries){
116
+ if(isTurnStart(entry)){emit(segment);segment=[];out.push(entry)}
117
+ else segment.push(entry)
118
+ }
119
+ emit(segment)
120
+ return out
121
+ }
122
+ function reasoningKey(data,index,fallback){return data?.turn!=null&&data?.step!=null?'reasoning:'+JSON.stringify([data.turn,data.step,index]):fallback}
123
+ const api={prepare,tool,toolEvent,reasoning,reasoningKey,group}
124
+ if(typeof module!=='undefined'&&module.exports)module.exports=api
125
+ else root.DshActivity=api
126
+ })(typeof window==='undefined'?globalThis:window)
package/public/admin.html CHANGED
@@ -7,6 +7,7 @@
7
7
  <title>DSH Remote · 管理</title>
8
8
  <script>/* 首帧前应用皮肤 */ (function(){try{var t=localStorage.getItem('dshTheme');if(t!=='default'&&t!=='dark'&&t!=='light'&&t!=='neutral'&&t!=='mono'){t=window.matchMedia('(prefers-color-scheme: light)').matches?'light':'default'}document.documentElement.setAttribute('data-theme',t)}catch(e){}})()</script>
9
9
  <link rel="stylesheet" href="../styles.css">
10
+ <link rel="stylesheet" href="../relay-settings.css">
10
11
  <style>
11
12
  .admin-wrap { max-width: 1180px; margin: 0 auto; padding: calc(env(safe-area-inset-top, 0px) + 14px) 14px 40px; }
12
13
  .admin-title {
@@ -459,6 +460,7 @@
459
460
  <button id="btn-save-port" class="mini-btn" data-i18n="savePort">保存</button>
460
461
  </div>
461
462
 
463
+ <div id="relay-settings"></div>
462
464
  <section id="host-ip-card" class="host-ip-card" aria-live="polite">
463
465
  <div class="host-ip-head">
464
466
  <div>
@@ -770,5 +772,7 @@
770
772
  <script src="../vendor/gsap/gsap.min.js"></script>
771
773
  <script src="../motion.js"></script>
772
774
  <script src="../admin.js"></script>
775
+ <script src="../relay-settings.js"></script>
776
+ <script>window.mountAdminRelaySettings?.()</script>
773
777
  </body>
774
778
  </html>
package/public/admin.js CHANGED
@@ -11,6 +11,10 @@ const pluginMode = location.pathname === '/remote'
11
11
  || location.pathname.startsWith('/remote/')
12
12
  || new URLSearchParams(location.search).get('embedded') === '1'
13
13
  const API = pluginMode ? '/remote/admin/api' : '/admin/api'
14
+ window.mountAdminRelaySettings = () => window.DshRelaySettings?.mount($('relay-settings'), {
15
+ connection: () => { const saved=token;return {url:route=>API+route,headers:adminHeaders({},saved),valid:()=>token===saved} },
16
+ path:'/relay', credentials:'same-origin'
17
+ })
14
18
  // 沙箱 iframe/隐私模式里 localStorage 可能抛 SecurityError, 不能让它杀死整个页面
15
19
  const store = {
16
20
  get(k) { try { return localStorage.getItem(k) } catch { return null } },
@@ -177,6 +177,14 @@
177
177
  "publishedAt": "2026-09-19T08:03:06+08:00",
178
178
  "actionUrl": "https://github.com/Blank-not-black/dsh-Remote/releases/tag/v0.7.0-rc.1",
179
179
  "actionText": "下载 0.7.0-rc.1 测试版"
180
+ },
181
+ {
182
+ "id": "2026-10-16-0.8.0-relay-trial",
183
+ "title": "0.8.0 预告 · 云中转试测招募",
184
+ "content": "感谢各位开发者持续使用 DSH Remote,也感谢大家耐心反馈问题和建议。这些来自实际使用的意见,是本次 0.8.0 调整的重要依据。\n\n0.8.0 主要变化\n① 整理为「会话、文件、更多」三个入口,整合待审批、待回答和常用操作。\n② 简化新建会话、工作区选择与设置流程,减少重复操作。\n③ 改进弱网状态反馈和断线恢复;结果未确认的操作不会自动重复发送。\n④ 增加聊天文本文件预览、改进上传体验,并修复 Windows 插件更新时的部分目录占用问题。\n\n目前 0.8.0-rc.2 已发布,正式版将根据试测反馈继续调整。本轮界面改动主要覆盖 Android 和手机、桌面 Web。\n\n云服务器中转试测\n测试版新增云中转:每位测试者连接自己的 DSH,在设置中填写个人中转密钥,绑定后即可通过专属公网地址连接。电脑上的 DSH 和 Remote 网关仍需保持运行。\n\n首批开放 5 个名额,测试周期约一周,具体有效期以授权通知为准。每位用户每日上传与下载合计 5GB,北京时间零点重置。我们主要收集连接成功率、响应延迟、实时输出与断线恢复方面的反馈。\n\n中转采用云端终止 TLS 的方式,运营者在技术上可接触经过的转发内容,请使用适合参与试测的环境和数据。\n\n如何申请\n请复制下方完整申请模板,打开 App 顶部「反馈 → 直接反馈」,选择「其他」,将模板粘贴到反馈内容栏,填写后提交。选择题请保留一个选项即可。\n\n【云中转试测申请】\n昵称:\n邮箱:\nQQ群内昵称/备注名:\nQQ号:\n电脑系统:Windows/Linux/macOS/其他\n主要问题:公网连接困难/延迟高/经常断线/传输慢/希望体验\n是否愿意反馈试测问题:愿意/暂时无法保证\n手机系统及补充说明(选填):\n\n填写的信息仅用于测试资格安排和试测联络,请勿提交中转密钥、Remote 令牌或模型 API Key。感谢大家继续帮助 DSH Remote 改善使用体验!",
185
+ "minVersion": "",
186
+ "maxVersion": "",
187
+ "publishedAt": "2026-10-16T09:27:32.340Z"
180
188
  }
181
189
  ]
182
190
  }