dsh-remote-plugin 0.7.6 → 0.8.0-rc.2

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.2",
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 {
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 } },
package/public/app.js CHANGED
@@ -513,7 +513,10 @@ async function rpc(method, payload = {}, timeoutMs = 45000) {
513
513
  if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
514
514
  opts.signal = AbortSignal.timeout(timeoutMs)
515
515
  }
516
- const res = await fetch(apiUrl('/api/' + method), opts)
516
+ const operation = window.DshOperations?.supports(method) && activeGatewayCapability('operations') === true
517
+ const connection = operation ? captureConnection() : null
518
+ const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
519
+ const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
517
520
  if (res.status === 401) throw new Error('AUTH')
518
521
  if (!res.ok) throw new Error('HTTP ' + res.status)
519
522
  const full = await res.json()
@@ -1402,7 +1405,7 @@ async function pollKind(kind, cancellation) {
1402
1405
  const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
1403
1406
  const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1404
1407
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }
1405
- res = signal ? await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000`), { signal, headers }) : await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000`), { headers })
1408
+ res = await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000&epoch=${encodeURIComponent(cursors[kind + "Epoch"] || "")}`), { ...(signal ? { signal } : {}), headers })
1406
1409
  } catch { return }
1407
1410
  if (!valid()) return
1408
1411
  if (res.status === 401) { authFailure(); return }
@@ -1413,7 +1416,7 @@ async function pollKind(kind, cancellation) {
1413
1416
  if (!data || !Array.isArray(data.events)) return
1414
1417
  // 网关重启或客户端离线过久后,游标可能落后于内存环形缓冲;
1415
1418
  // 从当前缓冲重新接收,并刷新权威会话列表,避免静默漏事件。
1416
- const reset = data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
1419
+ const reset = data.reset === true || (!!data.epoch && !!cursors[kind + 'Epoch'] && cursors[kind + 'Epoch'] !== data.epoch) || data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
1417
1420
  if (reset) {
1418
1421
  state.pollSeq[kind] = 0
1419
1422
  if (kind === 'mux') {
@@ -1424,6 +1427,8 @@ async function pollKind(kind, cancellation) {
1424
1427
  scheduleRefresh()
1425
1428
  if (state.current) void resyncCurrentSession()
1426
1429
  }
1430
+ if (data.epoch) cursors[kind + 'Epoch'] = data.epoch
1431
+ for (const frame of data.baseline || []) { if (kind === 'mux') onMuxFrame(frame); else onHostFrame(frame) }
1427
1432
  for (const item of data.events) {
1428
1433
  if (item.seq > (state.pollSeq[kind] || 0)) {
1429
1434
  state.pollSeq[kind] = item.seq
@@ -1585,6 +1590,7 @@ function setCompactionStatus(sessionId, next) {
1585
1590
  }
1586
1591
  if (previous?.active && previous.notify && next?.notify !== false && ['complete', 'failed'].includes(next?.phase)) {
1587
1592
  const command = previous.command || 'compact'
1593
+ if (command === 'export' && next?.phase === 'complete' && state.current === sessionId && typeof downloadSessionExport === 'function') void downloadSessionExport(sessionId)
1588
1594
  if (next?.phase === 'failed') toast(command === 'compact'
1589
1595
  ? t('session.compactFailed', { msg: next.message || t('send.failed') })
1590
1596
  : t('session.commandFailed', { command, msg: next.message || t('send.failed') }), 'err')
@@ -2040,34 +2046,41 @@ function renderWorkspaceNavigation() {
2040
2046
  if ($('modal-new-session') && !$('modal-new-session').classList.contains('hidden')) renderNewSessionWorkspace()
2041
2047
  return items
2042
2048
  }
2043
- async function refreshWorkbench() {
2049
+ async function refreshWorkbench({ discover = false } = {}) {
2044
2050
  const connection = captureConnection(), request = ++workbenchRequest
2045
2051
  const valid = () => connection.valid() && request === workbenchRequest
2052
+ const sharedRead = (name, read) => window.DshNetwork?.shareRead ? window.DshNetwork.shareRead(JSON.stringify([connection.server, connection.token, name]), read) : read()
2046
2053
  if (!state.token) return
2054
+ const workspaceRead = sharedRead('workspace.list', () => connection.valid() ? rpc('workspace.list', {}) : null).catch(() => null)
2047
2055
  try {
2048
- const res = await fetch(apiUrl('/workbench'), {
2049
- headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }
2056
+ const target = apiUrl('/workbench')
2057
+ const res = await sharedRead('workbench', async () => {
2058
+ if(!connection.valid())return {ok:false,value:null}
2059
+ const response = await fetch(target, {
2060
+ headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }, signal: AbortSignal.timeout(10000)
2061
+ })
2062
+ return { ok: response.ok, value: await response.json().catch(() => null) }
2050
2063
  })
2051
2064
  if (!valid()) return
2052
2065
  if (res.ok) {
2053
- const value = await res.json().catch(() => null)
2066
+ const value = res.value
2054
2067
  if (!valid()) return
2055
2068
  if (value && typeof value.bound === 'boolean') state.wb = value
2056
2069
  }
2057
2070
  } catch {}
2058
2071
  if (!valid()) return
2059
2072
  try {
2060
- const value = await rpc('workspace.list', {})
2073
+ const value = await workspaceRead
2061
2074
  if (!valid()) return
2062
- state.wbProjects = Array.isArray(value?.items) ? value.items : []
2063
- state.wbArchived = Array.isArray(value?.archivedSessionIds) ? value.archivedSessionIds : []
2075
+ if (value) state.wbProjects = Array.isArray(value.items) ? value.items : []
2076
+ if (value) state.wbArchived = Array.isArray(value.archivedSessionIds) ? value.archivedSessionIds : []
2064
2077
  } catch {
2065
2078
  if (!valid()) return
2066
2079
  state.wbProjects = []
2067
2080
  state.wbArchived = []
2068
2081
  }
2069
2082
  // 以磁盘实际目录为准同步工作台项目:删除目录后不再残留,新增子目录自动收纳。
2070
- if (state.wb?.bound && state.wb.path) {
2083
+ if (discover && state.wb?.bound && state.wb.path) {
2071
2084
  try {
2072
2085
  const listRes = await fetch(fsApiUrl('/list', { path: state.wb.path }), { headers: fsHeaders() })
2073
2086
  if (!valid()) return
@@ -2131,7 +2144,7 @@ function renderWorkbench() {
2131
2144
  const open = !!state.wbOpenProjects[id]
2132
2145
  const sessions = orderedWorkspaceSessions(id, (w.sessionIds || []).map(sid => state.byId.get(sid)).filter(isVisibleSession).filter(s => !archivedSet.has(s.sessionId)))
2133
2146
  const body = open ? `<div class="wb-sessions">${sessions.length ? sessions.map(s => `
2134
- <div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}">
2147
+ <div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}" role="button" tabindex="0" aria-label="${esc(sessionLabelOf(s))}">
2135
2148
  <button class="wb-session" type="button" data-wb-session="${esc(s.sessionId)}" data-motion-key="${esc(s.sessionId)}">
2136
2149
  <span class="wb-session-drag-handle" data-reorder-handle aria-hidden="true">⠿</span>
2137
2150
  <span class="wb-session-title">${esc(sessionLabelOf(s))}</span>
@@ -2236,7 +2249,7 @@ function renderSessions() {
2236
2249
  const badge = goal ? `<span class="sc-badge ${goal.phase === 'active' ? 'goal-active' : ''}">${esc(t('sessions.goalBadge', { phase: goal.phase || '?' }))}</span>` : ''
2237
2250
  const queueBadge = queueN ? `<span class="sc-badge">${esc(t('sessions.queueBadge', { n: queueN }))}</span>` : ''
2238
2251
  const archiveButton = archivedSet.has(s.sessionId) ? '' : `<button type="button" class="sc-archive-btn" data-archive-session="${esc(s.sessionId)}">${esc(t('session.archive'))}</button>`
2239
- return `<div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}">
2252
+ return `<div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}" role="button" tabindex="0" aria-label="${esc(sessionLabelOf(s))}">
2240
2253
  <div class="session-card ${state.current === s.sessionId ? 'current' : ''}">
2241
2254
  <div class="sc-title">${esc(title)}</div>
2242
2255
  <div class="sc-meta">
@@ -3067,7 +3080,7 @@ async function runSlashCommand(text) {
3067
3080
  const res = await fetch(apiUrl('/remote/api/command'), {
3068
3081
  method: 'POST',
3069
3082
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
3070
- body: JSON.stringify({ sessionId, line: clean }),
3083
+ body: JSON.stringify({ sessionId, line: clean, async: true }),
3071
3084
  ...(signal ? { signal } : {})
3072
3085
  })
3073
3086
  if (!connection.valid()) return true
@@ -3081,7 +3094,7 @@ async function runSlashCommand(text) {
3081
3094
  if (data?.ok === false) { toast(data.message || t('send.failed'), 'err'); return true }
3082
3095
  if (data?.ok && data.executed === true) {
3083
3096
  if (data.accepted) {
3084
- if (command === 'compact') {
3097
+ if (command === 'compact' || command === 'export') {
3085
3098
  setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
3086
3099
  } else {
3087
3100
  state.pendingCommands[sessionId] = command
@@ -3209,11 +3222,13 @@ function composerIsBusy() {
3209
3222
  return !!state.byId.get(state.current)?.running || (state.queues[state.current] || []).some(item => item.placement === 'queued')
3210
3223
  }
3211
3224
  function composerSendMode(alternate = false) {
3225
+ if (window.DshWorkflow?.isMounted()) return alternate && composerIsBusy() ? 'steer' : 'queue'
3212
3226
  if (!steerSendingEnabled() || !composerIsBusy()) return 'queue'
3213
3227
  const preferred = LS.get('busySendMode', 'queue') === 'steer' ? 'steer' : 'queue'
3214
3228
  return alternate ? (preferred === 'queue' ? 'steer' : 'queue') : preferred
3215
3229
  }
3216
3230
  function renderComposerSend() {
3231
+ window.DshWorkflow?.update()
3217
3232
  const enabled = steerSendingEnabled() && composerIsBusy()
3218
3233
  const mode = composerSendMode()
3219
3234
  for (const id of ['btn-send', 'btn-fs-send']) {
@@ -3232,6 +3247,7 @@ function renderComposerSend() {
3232
3247
  node.classList.toggle('hidden', !node.textContent)
3233
3248
  node.dataset.phase = feedback?.phase || 'hint'
3234
3249
  }
3250
+ window.DshWorkflow?.update()
3235
3251
  }
3236
3252
  function setComposerSendFeedback(context, key, phase, message = '') {
3237
3253
  composerSendFeedback.set(context, { key, phase, message })
@@ -3308,7 +3324,7 @@ async function sendSessionContent(text, images, requestedMode = 'queue') {
3308
3324
  if ((!clean && !images.length) || !state.current || composerSending) return false
3309
3325
  const sessionId = state.current
3310
3326
  const context = composerContext()
3311
- const mode = requestedMode === 'steer' && steerSendingEnabled() && composerIsBusy() ? 'steer' : 'queue'
3327
+ const mode = requestedMode === 'steer' && (window.DshWorkflow?.isMounted() || steerSendingEnabled()) && composerIsBusy() ? 'steer' : 'queue'
3312
3328
  if (mode === 'steer' && clean.startsWith('/')) {
3313
3329
  setComposerSendFeedback(context, 'send.steerSlash', 'error')
3314
3330
  return false
@@ -3582,6 +3598,7 @@ async function newSession() {
3582
3598
  if (!workspaceItems().length) await refreshWorkbench()
3583
3599
  const preferred = workspaceById(state.workspaceFilter)?.workspaceId || LS.get('lastNewSessionWorkspaceV1', '')
3584
3600
  renderNewSessionWorkspace(preferred)
3601
+ if (workspaceById(state.workspaceFilter) || workspaceItems().length === 1) return createSessionInWorkspace()
3585
3602
  $('modal-new-session').classList.remove('hidden')
3586
3603
  }
3587
3604
  function renderNewSessionWorkspace(preferredId = '') {
@@ -3619,9 +3636,12 @@ async function createSessionInWorkspace() {
3619
3636
  LS.set('lastNewSessionWorkspaceV1', workspaceId)
3620
3637
  closeNewSessionModal()
3621
3638
  toast(t('home.created'), 'ok')
3622
- await refreshSessions()
3623
- if (!connection.valid()) return
3624
- openSession(v.sessionId)
3639
+ const workspace = workspaceById(workspaceId)
3640
+ const session = { sessionId: v.sessionId, cwd: workspace?.path || '', running: false, projections: { values: {} } }
3641
+ state.byId.set(session.sessionId, session)
3642
+ state.sessions.unshift(session)
3643
+ void openSession(session.sessionId)
3644
+ void refreshSessions()
3625
3645
  } finally { createSessionInWorkspace.busy = false; button.disabled = false }
3626
3646
  }
3627
3647
 
@@ -3759,6 +3779,7 @@ window.addEventListener('offline',()=>startOverviewDetection(true))
3759
3779
  document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}})
3760
3780
 
3761
3781
  function renderOverview() {
3782
+ window.DshWorkflow?.update()
3762
3783
  const ring = $('overview-pulse-ring')
3763
3784
  if (!ring) return
3764
3785
  const checks = overviewChecks()
@@ -3795,7 +3816,7 @@ function renderOverview() {
3795
3816
  ...state.questions.map(q => ({ kind: 'question', item: q }))
3796
3817
  ]
3797
3818
  $('overview-attention-count').textContent = pending.length ? t('overview.pendingCount', { n: pending.length }) : '—'
3798
- $('overview-attention-list').innerHTML = pending.length ? pending.slice(0, 3).map(({ kind, item }) => {
3819
+ $('overview-attention-list').innerHTML = pending.length ? pending.map(({ kind, item }) => {
3799
3820
  const title = sessionLabelOf(state.byId.get(item.sessionId))
3800
3821
  if (kind === 'approval') return `<div class="overview-attention-item" data-overview-approval="${esc(item.approvalId)}">
3801
3822
  <span class="overview-item-mark">⌁</span><span class="overview-item-copy"><span class="overview-item-title">${esc(item.toolName || t('tool.default'))}</span><span class="overview-item-desc">${esc(approvalDetail(item))} · ${esc(title)}</span></span>
@@ -4534,6 +4555,8 @@ async function runFsUpload(up) {
4534
4555
  const xhr = new XMLHttpRequest()
4535
4556
  up.xhr = xhr
4536
4557
  xhr.open('POST', fsApiUrl('/upload', params))
4558
+ xhr.timeout = window.DshNetwork?.profile().weak ? 180000 : 90000
4559
+ xhr.ontimeout = () => { if (up.xhr === xhr) up.xhr = null; reject(new Error('上传等待超时,可查询进度后继续')) }
4537
4560
  xhr.setRequestHeader('authorization', 'Bearer ' + state.token)
4538
4561
  xhr.setRequestHeader('x-dsh-remote-client', CAP?.isNativePlatform?.() ? 'app' : 'web')
4539
4562
  if (CLIENT_ID) xhr.setRequestHeader('x-dsh-remote-client-id', CLIENT_ID)
@@ -4586,7 +4609,8 @@ async function runFsUpload(up) {
4586
4609
 
4587
4610
  while (up.offset < up.size) {
4588
4611
  if (up.cancelled) return
4589
- const end = Math.min(up.offset + FS_CHUNK_SIZE, up.size)
4612
+ const chunkSize = up.chunkSize || (window.DshNetwork?.profile().weak ? 256 * 1024 : FS_CHUNK_SIZE)
4613
+ const end = Math.min(up.offset + chunkSize, up.size)
4590
4614
  const blob = up.file.slice(up.offset, end)
4591
4615
  const before = hasher.clone()
4592
4616
  const chunkBytes = new Uint8Array(await blob.arrayBuffer())
@@ -4598,7 +4622,10 @@ async function runFsUpload(up) {
4598
4622
  const params = { path: up.path, name: up.name, session: up.session, offset: String(up.offset), size: String(up.size) }
4599
4623
  if (isLast) { params.finish = '1'; params.sha256 = hasher.hex() }
4600
4624
  if (overwrite) params.overwrite = '1'
4625
+ const startedAt = Date.now()
4601
4626
  const r = await uploadChunk(params, blob)
4627
+ const elapsed = Date.now() - startedAt
4628
+ up.chunkSize = elapsed > 15000 ? Math.max(65536, Math.floor(chunkSize / 2)) : elapsed < 2000 ? Math.min(FS_CHUNK_SIZE, chunkSize * 2) : chunkSize
4602
4629
  if (r.status === 401) { fsAuthError(401); return }
4603
4630
  if (r.status === 200 && r.json.offset != null) { up.offset = r.json.offset; continue }
4604
4631
  if (r.status === 201) {
@@ -4690,8 +4717,8 @@ async function runFsUpload(up) {
4690
4717
  toast(e.message, 'err')
4691
4718
  return
4692
4719
  }
4693
- hideFsProgress()
4694
- setFsButtons(false)
4720
+ up.paused = true
4721
+ setFsButtons(true, true)
4695
4722
  toast(t('fs.uploadInterrupted', { msg: e.message }), 'err')
4696
4723
  }
4697
4724
  }
@@ -5188,6 +5215,7 @@ async function fetchAnnouncements() {
5188
5215
  state.announcements = normalized.sort((a, b) => Number(b.publishedAt || 0) - Number(a.publishedAt || 0))
5189
5216
  storeAnnouncementHistory(normalized)
5190
5217
  renderAnnouncementBoard()
5218
+ if (window.DshWorkflow?.isMounted()) return false
5191
5219
  const seen = readSeenAnnouncements()
5192
5220
  const items = normalized.filter(item => !seen[item.id])
5193
5221
  .sort((a, b) => b.publishedAt - a.publishedAt)
@@ -5321,7 +5349,7 @@ async function checkUpdate(silent) {
5321
5349
  const res = await fetch(base + '/update.json?t=' + Date.now() + '&local=' + encodeURIComponent(state.localVersion))
5322
5350
  if (!res.ok) throw new Error('HTTP ' + res.status)
5323
5351
  const info = await res.json()
5324
- openNotesModal(info)
5352
+ if (!silent || !window.DshWorkflow?.isMounted()) openNotesModal(info)
5325
5353
  if (info.version && cmpVersion(info.version, state.localVersion) > 0) {
5326
5354
  state.updateInfo = info
5327
5355
  const hasNotes = !!(info.notes && String(info.notes).trim())
@@ -6289,6 +6317,8 @@ async function openModelConfigDocument() {
6289
6317
  }
6290
6318
  /* ---------------- 视图切换 ---------------- */
6291
6319
  function showView(id) {
6320
+ window.DshWorkflow?.close()
6321
+ if (window.DshWorkflow?.isMounted() && id === 'view-activity') id = 'view-home'
6292
6322
  if (id !== 'view-session') conversationView?.pause()
6293
6323
  if (id !== 'view-session' && document.body.classList.contains('in-session') && state.current) void archiveEmptySessionOnLeave(state.current)
6294
6324
  for (const v of ['view-home', 'view-files', 'view-session', 'view-activity', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
@@ -7113,7 +7143,11 @@ function bindUi() {
7113
7143
  if (first.matches('button')) first.focus({ preventScroll: true })
7114
7144
  }
7115
7145
  })
7116
- // 会话列表点击
7146
+ // 会话列表点击与键盘激活共享目标。
7147
+ $('session-list').addEventListener('keydown', event => {
7148
+ const card = event.target.closest('[data-session-swipe]')
7149
+ if (card && event.target === card && ['Enter', ' '].includes(event.key)) { event.preventDefault(); void openSession(card.dataset.id) }
7150
+ })
7117
7151
  $('session-list').addEventListener('click', (e) => {
7118
7152
  if (swipeSuppressClickUntil > Date.now()) { swipeSuppressClickUntil = 0; return }
7119
7153
  if (e.target.closest('[data-archived-toggle]')) {
@@ -7560,7 +7594,7 @@ function bindUi() {
7560
7594
 
7561
7595
  for (const id of ['history', 'question-body']) window.DshChatFiles?.bind($(id), () => {
7562
7596
  const c=captureConnection(),sessionId=id==='history'?state.current:state.questionModal?.sessionId
7563
- return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:!!CAP?.isNativePlatform?.(),headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,
7597
+ return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:!!CAP?.isNativePlatform?.(),headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,preview:(path,name)=>window.DshWorkflow?.preview({...c,headers:{authorization:'Bearer '+c.token}},path,name),
7564
7598
  valid:()=>c.valid()&&sessionId===(id==='history'?state.current:state.questionModal?.sessionId) }
7565
7599
  })
7566
7600
  initCustomSelects()
@@ -7617,6 +7651,83 @@ async function boot() {
7617
7651
  }
7618
7652
 
7619
7653
  document.addEventListener('DOMContentLoaded', boot)
7654
+ document.addEventListener('DOMContentLoaded', mountWorkflow)
7655
+
7656
+ function mountWorkflow() {
7657
+ window.DshWorkflow?.mount({
7658
+ desktop: false,
7659
+ start: () => { if (!$('view-activity').classList.contains('hidden')) showView('view-home') },
7660
+ snapshot: () => ({ token: !!state.token, host: currentServerEntry()?.note || state.server || location.host,
7661
+ gateway: activeGatewayHealth()?.ok || !!state.streamsOk?.mux, dsh: dshReachable(),
7662
+ mux: !!state.streamsOk?.mux, hostEvents: !!state.streamsOk?.host,
7663
+ pending: state.approvals.length + state.questions.length, busy: composerIsBusy(), sending: composerSending }),
7664
+ settings: name => { showView('view-settings'); showSettingsPage(name) },
7665
+ plugins: () => showView('view-plugins'), models: loadSessionModels, send: sendMessage,
7666
+ feedback: openFeedbackModal,
7667
+ browse: () => { closeNewSessionModal(); showView('view-files') },
7668
+ register: async () => {
7669
+ const connection=captureConnection(), path=state.fs.path
7670
+ if(!path)return toast('请先选择主机目录','err')
7671
+ try {
7672
+ const value=await rpc('workspace.create',{path})
7673
+ if(!connection.valid()||!value?.workspace)return
7674
+ state.wbProjects=[...state.wbProjects.filter(w=>w.workspaceId!==value.workspace.workspaceId),value.workspace]
7675
+ state.workspaceFilter=value.workspace.workspaceId;closeWorkspaceModal();await newSession()
7676
+ }catch(error){if(connection.valid())toast(error.message,'err')}
7677
+ },
7678
+ command: runSlashCommand, refresh: refreshAll, retry: () => { startOverviewDetection(true); void refreshAll() },
7679
+ operations: () => { const connection=captureConnection(); return { url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid } },
7680
+ discover: () => { if (confirm('登记当前绑定目录下的子目录为工作区?')) void refreshWorkbench({ discover: true }) },
7681
+ files: () => {
7682
+ const workspace = workspaceForSession(state.byId.get(state.current))
7683
+ if (workspace) return openWorkspaceFiles(workspace.workspaceId)
7684
+ const cwd = sessionCwd(state.byId.get(state.current))
7685
+ if (!cwd) return toast('当前会话没有工作目录', 'err')
7686
+ state.fs.loaded = true; showView('view-files'); void loadFs(cwd, { resetRoot: true })
7687
+ },
7688
+ clear: clearWorkflowData,
7689
+ admin: () => {
7690
+ const url = new URL(apiUrl('/admin/'), location.href)
7691
+ // Open authenticated management through its own login flow. No credential
7692
+ // in a newly created URL, browser history, or referrer.
7693
+ window.open(url.href, '_blank', 'noopener,noreferrer')
7694
+ },
7695
+ recover: (row, receipt) => {
7696
+ const value = receipt.result?.result?.value
7697
+ if (row.method === 'session.create' && value?.sessionId) void openSession(value.sessionId)
7698
+ if (row.sessionId === state.current) void resyncCurrentSession()
7699
+ },
7700
+ })
7701
+ }
7702
+
7703
+ async function clearWorkflowData(kind) {
7704
+ const english = window.I18N?.lang === 'en'
7705
+ const messages = { history: english ? 'Clear cached conversation history on this device?' : '清除这台设备的会话历史缓存?主机记录保留。',
7706
+ connection: english ? 'Remove the current address and its saved credential? Other addresses remain.' : '移除当前地址和保存的凭证?其他连接条目保留。',
7707
+ all: english ? 'Clear all Remote settings and credentials on this device and stop background reminders?' : '清除本机全部 Remote 配置与凭证,并停止后台轮询和提醒?主机数据保留。' }
7708
+ if (!confirm(messages[kind])) return
7709
+ if (kind === 'history') {
7710
+ clearTimeout(scheduleHistoryCacheSave._t)
7711
+ await window.DshHistory.cacheClear()
7712
+ for (let i=localStorage.length-1;i>=0;i--) { const key=localStorage.key(i); if (/^dsh-remote-(?:sessions|history)/.test(key)) localStorage.removeItem(key) }
7713
+ return toast(english ? 'History cache cleared' : '历史缓存已清除', 'ok')
7714
+ }
7715
+ window.NativeBackground?.saveBackgroundConfig?.(JSON.stringify({ enabled:false, base:'', token:'', clientId:'', intervalMin:1, notifyTaskDone:false }))
7716
+ window.NativeBackground?.setPendingNotificationsEnabled?.(false)
7717
+ if (kind === 'connection') {
7718
+ const current = currentServerEntry()
7719
+ if (current) state.servers = state.servers.filter(server => server.id !== current.id)
7720
+ state.groupActive[state.activeGroup] = ''
7721
+ state.token = ''; state.server = ''; LS.del('token'); LS.del('server'); saveServers()
7722
+ closeStream('mux'); closeStream('host'); stopPolling(); renderServers(); showView('view-settings'); showSettingsPage('servers')
7723
+ return
7724
+ }
7725
+ await cancelPeakReminders()
7726
+ clearTimeout(scheduleHistoryCacheSave._t)
7727
+ await window.DshHistory.cacheClear()
7728
+ window.DshWorkflow.clearStorage()
7729
+ location.reload()
7730
+ }
7620
7731
 
7621
7732
  function openPluginPage(route = 'manage') {
7622
7733
  const connection = captureConnection()
@@ -20,7 +20,8 @@
20
20
  const a=block.attachment||block,raw=a.path||block.path||''
21
21
  const path=pathOf(raw)||(relativePath(raw)?raw:''),id=/^[a-f0-9]{64}$/.test(a.attachmentId||'')?a.attachmentId:''
22
22
  const name=a.name||block.name||'file'
23
- return `<div class="chat-file"><span class="chat-file-name">📎 ${esc(name)} <small>${esc(a.bytes??block.bytes??'')} bytes</small></span>${id||path?`<button type="button" ${id?'data-dsh-attachment="'+esc(id)+'"':''} ${path?'data-dsh-file-path="'+esc(path)+'"':''} data-dsh-file-name="${esc(name)}">下载文件</button>`:''}</div>`
23
+ const preview=path&&/\.(?:txt|md|markdown|log|json|jsonl|js|ts|py|css|html|htm|xml|yaml|yml|toml)$/i.test(name||path)&&Number(a.bytes??block.bytes??0)<=1048576
24
+ return `<div class="chat-file"><span class="chat-file-name">📎 ${esc(name)} <small>${esc(a.bytes??block.bytes??'')} bytes</small></span>${preview?`<button type="button" data-dsh-preview="1" data-dsh-file-path="${esc(path)}" data-dsh-file-name="${esc(name)}">预览</button>`:''}${id||path?`<button type="button" ${id?'data-dsh-attachment="'+esc(id)+'"':''} ${path?'data-dsh-file-path="'+esc(path)+'"':''} data-dsh-file-name="${esc(name)}">下载文件</button>`:''}</div>`
24
25
  }
25
26
  async function trackDownload(id,control,c) {
26
27
  // New shells expose DownloadManager state; older shells keep their enqueue-only contract.
@@ -45,6 +46,7 @@
45
46
  if(!c.valid())return
46
47
  if(!id&&!path){c.notice('无法定位文件,请核对当前会话的工作目录','err');return}
47
48
  const name=(control.dataset.dshFileName||path.split(/[\\/]/).pop()||'download').replace(/[\\/\x00-\x1f]/g,'_')
49
+ if(control.dataset.dshPreview){if(c.preview)await c.preview(path,name);return}
48
50
  const makeUrl=attachment=>{
49
51
  const url=new URL(c.server+(attachment?'/remote/api/session-file':'/fs/file'),root.location?.href)
50
52
  if(attachment){url.searchParams.set('sessionId',c.sessionId);url.searchParams.set('attachmentId',id)}
@@ -11,6 +11,8 @@
11
11
  <link rel="stylesheet" href="../skills.css">
12
12
  <link rel="stylesheet" href="../extensions.css">
13
13
  <link rel="stylesheet" href="../insights.css">
14
+ <link rel="stylesheet" href="../workflow.css">
15
+ <link rel="stylesheet" href="../relay-settings.css">
14
16
  </head>
15
17
  <body>
16
18
  <div class="ds-app" id="ds-app">
@@ -270,6 +272,7 @@
270
272
  </div>
271
273
 
272
274
  <div id="settings-page-servers" class="ds-settings hidden" data-motion-panel>
275
+ <div id="relay-settings"></div>
273
276
  <div class="ds-setting-row" data-settings-back style="cursor:pointer">
274
277
  <button class="ds-btn" data-i18n="ds.back">‹ 返回</button>
275
278
  <div class="ds-setting-name" data-i18n="ds.groupServers">服务器</div>
@@ -770,6 +773,9 @@
770
773
  <script src="../history.js"></script>
771
774
  <script src="../link-check.js"></script>
772
775
  <script src="../network.js"></script>
776
+ <script src="../operations.js"></script>
777
+ <script src="../workflow.js"></script>
778
+ <script src="../relay-settings.js"></script>
773
779
  <script src="desktop.js"></script>
774
780
  </body>
775
781
  </html>