dsh-remote-plugin 0.7.5 → 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.
@@ -1,17 +1,87 @@
1
1
  /* Explicit user downloads only; attachment IDs never become filesystem paths. */
2
2
  (function(root,factory){const api=factory(root);if(typeof module==='object')module.exports=api;root.DshChatFiles=api})(typeof window!=='undefined'?window:globalThis,(root)=>{
3
3
  const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))
4
+ function relativePath(path) {
5
+ return typeof path==='string' && !!path && path.length<=4096 && !/[\x00-\x1f]/.test(path) && !/^(?:[a-z][a-z0-9+.-]*:|[\\/]|#|\?)/i.test(path)
6
+ && !/^[a-f0-9]{64}$/i.test(path) && !/[?#]/.test(path)
7
+ && (/^\.{1,2}[\\/]/.test(path) || /(?:^|[\\/])[^\\/]+\.[^\\/.]+$/.test(path))
8
+ }
4
9
  function pathOf(value,cwd='') {
5
10
  if(typeof value!=='string'||value.length>4096||/[\x00-\x1f]/.test(value))return ''
6
11
  let path=value.trim()
7
12
  if(/^file:/i.test(path)){try{const u=new URL(path);if(u.hostname&&u.hostname!=='localhost')return '';path=decodeURIComponent(u.pathname);if(/^\/[a-z]:\//i.test(path))path=path.slice(1)}catch{return ''}}
8
13
  if(/[\x00-\x1f]/.test(path))return ''
9
14
  if(/^(?:[a-z]:[\\/]|\/(?!\/))/i.test(path))return path
10
- if(/^\.{1,2}[\\/]/.test(path)){const base=pathOf(cwd);if(base)return base.replace(/[\\/]+$/,'')+'/'+path}
15
+ if(relativePath(path)){const base=pathOf(cwd);if(base)return base.replace(/[\\/]+$/,'')+'/'+path}
11
16
  return ''
12
17
  }
13
18
 
14
- function render(block){const a=block.attachment||block,path=pathOf(a.path||block.path)||(/^\.{1,2}[\\/]/.test(a.path||block.path||'')?(a.path||block.path):''),id=/^[a-f0-9]{64}$/.test(a.attachmentId||'')?a.attachmentId:'';const name=a.name||block.name||'file';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)+'"':'data-dsh-file-path="'+esc(path)+'"'} data-dsh-file-name="${esc(name)}">下载文件</button>`:''}</div>`}
15
- function bind(target,config){target.addEventListener('click',async event=>{const control=event.target.closest?.('[data-dsh-file-path],[data-dsh-attachment]');if(!control||!target.contains(control)||control.getAttribute('aria-busy')==='true')return;event.preventDefault();const c=config(),id=control.dataset.dshAttachment,path=pathOf(control.dataset.dshFilePath,c.cwd);if(!c.valid())return;if(!id&&!path){c.notice('无法定位文件,请核对当前会话的工作目录','err');return;}const name=(control.dataset.dshFileName||path.split(/[\\/]/).pop()||'download').replace(/[\\/\x00-\x1f]/g,'_');const url=new URL(c.server+(id?'/remote/api/session-file':'/fs/file'),root.location?.href);if(id){url.searchParams.set('sessionId',c.sessionId);url.searchParams.set('attachmentId',id)}else url.searchParams.set('path',path);control.setAttribute('aria-busy','true');try{const response=await fetch(url,{method:'HEAD',redirect:'error',headers:c.headers,signal:AbortSignal.timeout(15000)});if(!c.valid())return;if(!response.ok)throw Error(response.status===403?'主机不允许下载这个文件':response.status===404?'文件不存在或不属于当前会话':response.status===503?'主机版本暂不支持附件下载':'文件下载失败(HTTP '+response.status+')');if(c.native){if(!root.NativeFile?.downloadToDownloads)throw Error('当前 App 不支持系统下载');root.NativeFile.downloadToDownloads(url.href,name,c.token)}else{if(c.token)url.searchParams.set('token',c.token);const link=document.createElement('a');link.href=url.href;link.download=name;link.referrerPolicy='no-referrer';document.body.append(link);link.click();link.remove()}c.notice('已交给系统下载,请在下载目录查看','ok')}catch(error){if(c.valid())c.notice(error.message,'err')}finally{control.removeAttribute('aria-busy')}})}
16
- return {pathOf,render,bind}
19
+ function render(block) {
20
+ const a=block.attachment||block,raw=a.path||block.path||''
21
+ const path=pathOf(raw)||(relativePath(raw)?raw:''),id=/^[a-f0-9]{64}$/.test(a.attachmentId||'')?a.attachmentId:''
22
+ const name=a.name||block.name||'file'
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>`
25
+ }
26
+ async function trackDownload(id,control,c) {
27
+ // New shells expose DownloadManager state; older shells keep their enqueue-only contract.
28
+ for (;;) {
29
+ await new Promise(resolve=>setTimeout(resolve,1000))
30
+ if(!c.valid() || control.isConnected===false)return
31
+ const status=JSON.parse(root.NativeFile.getFileDownloadStatus(String(id))||'{}')
32
+ if(status.phase==='complete'){
33
+ control.textContent='下载完成 · 再次下载'
34
+ c.notice('下载完成:下载/dsh-remote/'+status.name,'ok');return
35
+ }
36
+ if(status.phase==='error')throw Error(status.error||'下载失败,请重试')
37
+ if(status.phase==='unknown')throw Error('系统下载任务已移除,请重试')
38
+ control.textContent=status.phase==='paused'?'下载暂停,等待网络…':'下载中…'
39
+ }
40
+ }
41
+ function bind(target,config){target.addEventListener('click',async event=>{
42
+ const control=event.target.closest?.('[data-dsh-file-path],[data-dsh-attachment]')
43
+ if(!control||!target.contains(control)||control.getAttribute('aria-busy')==='true')return
44
+ event.preventDefault()
45
+ const c=config(),id=control.dataset.dshAttachment,path=pathOf(control.dataset.dshFilePath,c.cwd)
46
+ if(!c.valid())return
47
+ if(!id&&!path){c.notice('无法定位文件,请核对当前会话的工作目录','err');return}
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}
50
+ const makeUrl=attachment=>{
51
+ const url=new URL(c.server+(attachment?'/remote/api/session-file':'/fs/file'),root.location?.href)
52
+ if(attachment){url.searchParams.set('sessionId',c.sessionId);url.searchParams.set('attachmentId',id)}
53
+ else url.searchParams.set('path',path)
54
+ return url
55
+ }
56
+ const head=url=>fetch(url,{method:'HEAD',redirect:'error',headers:c.headers,signal:AbortSignal.timeout(15000)})
57
+ const original=control.textContent
58
+ control.setAttribute('aria-busy','true')
59
+ try{
60
+ let url=makeUrl(!!id),response=await head(url)
61
+ if(!c.valid())return
62
+ // Only an explicit host path can back up an unsupported attachment endpoint.
63
+ if(id&&path&&[404,405,501,503].includes(response.status)){
64
+ url=makeUrl(false);response=await head(url);if(!c.valid())return
65
+ }
66
+ if(!response.ok)throw Error(response.status===403?'主机不允许下载这个文件':response.status===404?'文件不存在或不属于当前会话':[405,501,503].includes(response.status)?'主机版本暂不支持附件下载,请更新主机插件':'文件下载失败(HTTP '+response.status+')')
67
+ if(c.native){
68
+ if(!root.NativeFile?.downloadToDownloads)throw Error('当前 App 不支持系统下载,请更新 App')
69
+ const task=root.NativeFile.downloadToDownloads(url.href,name,c.token)
70
+ if(root.NativeFile.getFileDownloadStatus&&!task)throw Error('系统下载未能启动,请重试')
71
+ c.notice('已交给系统下载,请在下载目录查看','ok')
72
+ if(root.NativeFile.getFileDownloadStatus&&task){
73
+ control.textContent='下载中…'
74
+ await trackDownload(task,control,c)
75
+ }
76
+ }else{
77
+ if(c.token)url.searchParams.set('token',c.token)
78
+ const link=document.createElement('a');link.href=url.href;link.download=name;link.referrerPolicy='no-referrer'
79
+ document.body.append(link);link.click();link.remove()
80
+ c.notice('已交给浏览器下载,请在下载目录查看','ok')
81
+ }
82
+ }catch(error){
83
+ if(c.valid()){control.textContent=original;c.notice(error.message,'err')}
84
+ }finally{control.removeAttribute('aria-busy')}
85
+ })}
86
+ return {pathOf,relativePath,render,bind}
17
87
  })
@@ -297,9 +297,16 @@ button.ds-overview-attention-item, button.ds-overview-session-item { cursor:poin
297
297
  .ds-presets-guide { padding: 2px 8px 10px; font-size: 11px; line-height: 1.5; }
298
298
  .ds-session-cards { flex: none; max-height: 220px; overflow-y: auto; padding: 10px 22px 0; display: flex; flex-direction: column; gap: 8px; }
299
299
  .ds-session-cards:empty { display: none; }
300
- .ds-session-pending { flex:none; margin:10px 22px 0; padding:10px; border:1px solid var(--dsr-warning-line); border-radius:13px; background:var(--dsr-warning-soft); }
300
+ .ds-session-pending { flex:0 1 auto; min-height:0; max-height:30vh; max-height:30dvh; display:flex; flex-direction:column; margin:10px 22px 0; padding:10px; border:1px solid var(--dsr-warning-line); border-radius:13px; background:var(--dsr-warning-soft); }
301
301
  .ds-session-pending-head { display:flex; align-items:center; justify-content:space-between; gap:8px; margin-bottom:8px; color:var(--dsr-text); font-size:12px; font-weight:750; }
302
- .ds-session-pending-list { display:flex; flex-direction:column; gap:8px; }
302
+ .ds-session-pending-head { flex:none; }
303
+ .ds-session-pending-list { min-height:0; overflow-y:auto; overscroll-behavior:contain; display:flex; flex-direction:column; gap:8px; }
304
+ .ds-session-pending-list > * { flex:none; }
305
+ .ds-session-pending button.question { width:100%; text-align:left; color:inherit; cursor:pointer; font:inherit; }
306
+ .ds-question-card-head { display:flex; align-items:center; justify-content:space-between; gap:10px; margin-bottom:5px; }
307
+ .ds-question-card-head .ds-notif-head { min-width:0; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
308
+ .ds-question-card-head .ds-btn { flex:none; white-space:nowrap; }
309
+ .ds-question-summary { display:-webkit-box; -webkit-line-clamp:3; -webkit-box-orient:vertical; overflow:hidden; overflow-wrap:anywhere; font-size:13px; line-height:1.45; color:var(--dsr-muted); }
303
310
  .ds-session-pending .ds-notif-card { min-width:0; box-shadow:none; animation:none; }
304
311
  .ds-session-pending .ds-notif-title, .ds-session-pending .ds-notif-body { overflow-wrap:anywhere; word-break:break-word; }
305
312
  .ds-card { background: var(--dsr-panel); border: 1px solid var(--dsr-line); border-radius: 12px; padding: 10px 12px; }
@@ -536,6 +543,13 @@ button.ds-overview-attention-item, button.ds-overview-session-item { cursor:poin
536
543
  .ds-new-session-name { font-size: 13px; font-weight: 600; }
537
544
  .ds-new-session-path { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dsr-muted); font-size: 11.5px; }
538
545
  .ds-modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 12px; }
546
+ #modal-question .ds-modal-card { box-sizing:border-box; display:flex; flex-direction:column; min-height:0; max-height:calc(100dvh - 32px); overflow:hidden; }
547
+ #modal-question .ds-modal-title, #modal-question .ds-modal-actions { flex:none; }
548
+ #question-body { min-height:0; max-height:none; overscroll-behavior:contain; overflow-wrap:anywhere; }
549
+ #question-body > * { flex:none; }
550
+ #question-body .ds-q-option { min-height:36px; cursor:pointer; }
551
+ #question-body .ds-q-option > span { min-width:0; }
552
+ #question-body pre { white-space:pre-wrap; overflow-wrap:anywhere; }
539
553
  .ds-q-item { border: 1px solid var(--dsr-line); border-radius: 10px; padding: 9px 11px; }
540
554
  .ds-q-text { font-size: 13.5px; margin-bottom: 6px; }
541
555
  .ds-q-option { display: flex; gap: 7px; align-items: flex-start; font-size: 13px; padding: 3px 0; }
@@ -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>
@@ -561,11 +561,13 @@ function closeNotesModal() {
561
561
  if (notesVersion) { LS.set(NOTES_KEY, notesVersion); notesVersion = '' }
562
562
  }
563
563
  async function checkNotesOnStart() {
564
+ if (typeof window !== 'undefined' && window.DshWorkflow?.isMounted()) return
564
565
  try {
565
566
  const res = await fetch('../update.json?t=' + Date.now(), { cache: 'no-store' })
566
567
  if (!res.ok || res.redirected || !String(res.headers.get('content-type') || '').includes('application/json')) return
567
568
  const info = await res.json()
568
569
  if (!info || typeof info !== 'object' || !info.version) return
570
+ if (typeof window !== 'undefined' && window.DshWorkflow?.isMounted()) return
569
571
  openNotesModal(info)
570
572
  } catch {}
571
573
  }
@@ -661,7 +663,10 @@ async function rpc(method, payload = {}, timeoutMs = 45000) {
661
663
  if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
662
664
  opts.signal = AbortSignal.timeout(timeoutMs)
663
665
  }
664
- const res = await fetch(apiUrl('/api/' + method), opts)
666
+ const operation = window.DshOperations?.supports(method) && activeGatewayCapability('operations') === true
667
+ const connection = operation ? captureConnection() : null
668
+ const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
669
+ const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
665
670
  if (res.status === 401) throw new Error('AUTH')
666
671
  if (!res.ok) throw new Error('HTTP ' + res.status)
667
672
  const full = await res.json()
@@ -1390,7 +1395,7 @@ async function pollKind(kind, cancellation) {
1390
1395
  const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
1391
1396
  const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1392
1397
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
1393
- 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 })
1398
+ res = await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000&epoch=${encodeURIComponent(cursors[kind + "Epoch"] || "")}`), { ...(signal ? { signal } : {}), headers })
1394
1399
  } catch { return }
1395
1400
  if (!valid()) return
1396
1401
  if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
@@ -1399,13 +1404,15 @@ async function pollKind(kind, cancellation) {
1399
1404
  try { data = await res.json() } catch { return }
1400
1405
  if (!valid()) return
1401
1406
  if (!data || !Array.isArray(data.events)) return
1402
- const reset = data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
1407
+ 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)
1403
1408
  if (reset) {
1404
1409
  state.pollSeq[kind] = 0
1405
1410
  if (kind === 'mux') renderNotifStack()
1406
1411
  refreshSessions()
1407
1412
  if (state.current) void resyncCurrentSession()
1408
1413
  }
1414
+ if (data.epoch) cursors[kind + 'Epoch'] = data.epoch
1415
+ for (const frame of data.baseline || []) { if (kind === 'mux') onMuxFrame(frame); else onHostFrame(frame) }
1409
1416
  for (const item of data.events) {
1410
1417
  if (item.seq > (state.pollSeq[kind] || 0)) {
1411
1418
  state.pollSeq[kind] = item.seq
@@ -1466,7 +1473,11 @@ function onMuxFrame(full) {
1466
1473
  renderNotifStack()
1467
1474
  return
1468
1475
  }
1469
- if (f.type === 'question/resolved') { state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId); renderNotifStack(); return }
1476
+ if (f.type === 'question/resolved') {
1477
+ state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId)
1478
+ if (state.questionModal?.rpcId === f.questionRpcId) { $('modal-question').classList.add('hidden'); state.questionModal = null }
1479
+ renderNotifStack(); return
1480
+ }
1470
1481
  if (f.type === 'session/queue') { state.queues[f.sessionId] = f.items || []; renderQueue(); return }
1471
1482
  if (f.type === 'session/projection') { applyProjection(f.sessionId, f.key, f.value, f.seq); return }
1472
1483
  if (f.type === 'stream/error') toast(f.error?.message || 'stream error', 'err')
@@ -1517,6 +1528,7 @@ function setCompactionStatus(sessionId, next) {
1517
1528
  }
1518
1529
  if (previous?.active && previous.notify && next?.notify !== false && ['complete', 'failed'].includes(next?.phase)) {
1519
1530
  const command = previous.command || 'compact'
1531
+ if (command === 'export' && next?.phase === 'complete' && state.current === sessionId && typeof downloadSessionExport === 'function') void downloadSessionExport(sessionId)
1520
1532
  if (next?.phase === 'failed') toast(command === 'compact'
1521
1533
  ? t('ds.compactFailed', { msg: next.message || t('ds.sessionRecoveryFailed') })
1522
1534
  : t('ds.commandFailed', { command, msg: next.message || t('ds.sessionRecoveryFailed') }), 'err')
@@ -2388,7 +2400,7 @@ async function runSlashCommand(text) {
2388
2400
  const res = await fetch(apiUrl('/remote/api/command'), {
2389
2401
  method: 'POST',
2390
2402
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
2391
- body: JSON.stringify({ sessionId, line: clean }),
2403
+ body: JSON.stringify({ sessionId, line: clean, async: true }),
2392
2404
  ...(signal ? { signal } : {})
2393
2405
  })
2394
2406
  if (!connection.valid()) return true
@@ -2402,7 +2414,7 @@ async function runSlashCommand(text) {
2402
2414
  if (data?.ok === false) return true
2403
2415
  if (data?.ok === true && data.executed === true) {
2404
2416
  if (data.accepted) {
2405
- if (command === 'compact') {
2417
+ if (command === 'compact' || command === 'export') {
2406
2418
  setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2407
2419
  } else {
2408
2420
  state.pendingCommands[sessionId] = command
@@ -2422,7 +2434,7 @@ async function runSlashCommand(text) {
2422
2434
  return !connection.valid() || state.current !== sessionId
2423
2435
  }
2424
2436
 
2425
- async function sendMessage() {
2437
+ async function sendMessage(requestedMode = 'queue') {
2426
2438
  const input = $('composer')
2427
2439
  const originalText = input.value, text = originalText.trim()
2428
2440
  if (!text || !state.current) return
@@ -2438,7 +2450,7 @@ async function sendMessage() {
2438
2450
  setSessionRecovery('resuming')
2439
2451
  const v = await safeRpc('session.prompt', {
2440
2452
  sessionId,
2441
- mode: 'queue',
2453
+ mode: requestedMode === 'steer' && state.byId.get(sessionId)?.running ? 'steer' : 'queue',
2442
2454
  content: [{ type: 'text', text }]
2443
2455
  }, '')
2444
2456
  if (!valid()) return
@@ -2447,7 +2459,7 @@ async function sendMessage() {
2447
2459
  setSessionRecovery('ready'); noteSessionTurnTime(sessionId, Date.now()); renderSessions(); toast(t('ds.toastSent'), 'ok')
2448
2460
  }
2449
2461
  else setSessionRecovery('error')
2450
- } finally { pending.delete(history) }
2462
+ } finally { pending.delete(history); window.DshWorkflow?.update() }
2451
2463
  }
2452
2464
 
2453
2465
  async function cancelSession() {
@@ -2508,6 +2520,7 @@ async function archiveCurrentSession() {
2508
2520
  }
2509
2521
 
2510
2522
  function updateComposerStatus() {
2523
+ window.DshWorkflow?.update()
2511
2524
  const status = $('composer-status')
2512
2525
  if (!status) return
2513
2526
  const compact = activeCompaction()
@@ -2590,14 +2603,13 @@ function renderSessionPendingDesktop() {
2590
2603
  <div class="ds-notif-body">${esc(desktopApprovalDetail(item))}</div>
2591
2604
  <div class="ds-notif-actions"><button type="button" class="ds-btn allow" data-session-approve="1">${t('ds.allow')}</button><button type="button" class="ds-btn reject" data-session-approve="0">${t('ds.reject')}</button></div>
2592
2605
  </article>`
2593
- return `<article class="ds-notif-card question" data-session-question="${esc(item.rpcId)}">
2594
- <div class="ds-notif-head">❓ ${t('ds.questionNotify')}</div>
2595
- <div class="ds-notif-title">${esc((item.questions || []).map(question => question.question).filter(Boolean).join(' / '))}</div>
2596
- <div class="ds-notif-actions"><button type="button" class="ds-btn" data-session-answer>${t('ds.submit')}</button></div>
2597
- </article>`
2606
+ return `<button type="button" class="ds-notif-card question" data-session-question="${esc(item.rpcId)}" aria-haspopup="dialog">
2607
+ <span class="ds-question-card-head"><span class="ds-notif-head">❓ ${esc(item.questions?.[0]?.header || t('ds.questionNotify'))}</span><span class="ds-btn">${t('ds.submit')}</span></span>
2608
+ <span class="ds-question-summary">${esc(questionSummary(item))}</span>
2609
+ </button>`
2598
2610
  }).join('')}</div>`
2599
2611
  box.querySelectorAll('[data-session-approve]').forEach(button => button.addEventListener('click', () => approveApproval(button.closest('[data-session-approval]')?.dataset.sessionApproval || '', button.dataset.sessionApprove === '1')))
2600
- box.querySelectorAll('[data-session-answer]').forEach(button => button.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === button.closest('[data-session-question]')?.dataset.sessionQuestion))))
2612
+ box.querySelectorAll('[data-session-question]').forEach(button => button.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === button.dataset.sessionQuestion))))
2601
2613
  }
2602
2614
  function renderNotifStack() {
2603
2615
  const stack = $('notif-stack')
@@ -2660,17 +2672,27 @@ async function approveApproval(id, allow) {
2660
2672
  state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
2661
2673
  renderNotifStack()
2662
2674
  }
2675
+ function questionSummary(q) {
2676
+ return (q.questions || []).map(item => String(item.question || '').replace(/\[([^\]]+)\]\([^)]+\)/g, '$1').replace(/[*_`#>]/g, '')).join(' / ').replace(/\s+/g, ' ').trim().slice(0, 240)
2677
+ }
2678
+
2679
+ function questionMarkup(item) {
2680
+ const text = String(item.question || '')
2681
+ return (item.header ? `<strong>${esc(item.header)}</strong>` : '') + (window.mdToHtml ? window.mdToHtml(text, { richContent: false, fileLinks: true }) : esc(text))
2682
+ }
2683
+
2663
2684
  function openQuestionModal(q) {
2664
2685
  if (!q) return
2665
2686
  state.questionModal = q
2666
2687
  $('question-body').innerHTML = q.questions.map((item, i) => `
2667
2688
  <div class="ds-q-item">
2668
- <div class="ds-q-text">${esc(item.header ? item.header + ':' : '')}${esc(item.question)}</div>
2689
+ <div class="ds-q-text md">${questionMarkup(item)}</div>
2669
2690
  ${(item.options || []).map((o, j) => `
2670
2691
  <label class="ds-q-option"><input type="${item.multiSelect ? 'checkbox' : 'radio'}" name="q${i}" value="${esc(o.label)}"><span>${esc(o.label)}${o.description ? `<div class="muted">${esc(o.description)}</div>` : ''}</span></label>`).join('')}
2671
2692
  <textarea rows="2" placeholder="${t('ds.questionCustom')}" data-qcustom="${i}"></textarea>
2672
2693
  </div>`).join('')
2673
2694
  $('modal-question').classList.remove('hidden')
2695
+ $('question-body').scrollTop = 0
2674
2696
  }
2675
2697
  async function submitQuestion() {
2676
2698
  const connection = captureConnection()
@@ -3023,13 +3045,15 @@ function commitWorkspaceSessionOrder(workspaceId, order) {
3023
3045
  renderWorkbench()
3024
3046
  toast(t('ds.wbOrderSaved'), 'ok')
3025
3047
  }
3026
- async function refreshWorkbench({ silent = false } = {}) {
3048
+ async function refreshWorkbench({ silent = false, discover = false } = {}) {
3027
3049
  const connection = captureConnection(), request = ++workbenchRequest
3028
3050
  const valid = () => connection.valid() && request === workbenchRequest
3051
+ const sharedRead = (name, read) => window.DshNetwork?.shareRead ? window.DshNetwork.shareRead(JSON.stringify([connection.server, connection.token, name]), read) : read()
3029
3052
  if (!state.token) { renderWorkbench(); return }
3053
+ const workspaceRead = sharedRead('workspace.list', () => connection.valid() ? safeRpc('workspace.list', {}, '') : null)
3030
3054
  let wb = null
3031
3055
  try {
3032
- wb = await wbGateway('GET', '/workbench')
3056
+ wb = await sharedRead('workbench', () => connection.valid() ? wbGateway('GET', '/workbench') : null)
3033
3057
  if (!valid()) return
3034
3058
  state.wb.apiMissing = false
3035
3059
  } catch (e) {
@@ -3038,10 +3062,12 @@ async function refreshWorkbench({ silent = false } = {}) {
3038
3062
  if (!silent) toast(t('wb.loadFailed', { msg: e.message }), 'err')
3039
3063
  if (!state.wb.bound && /404/.test(e.message)) state.wb.apiMissing = true
3040
3064
  }
3041
- const wl = await safeRpc('workspace.list', {}, '')
3065
+ const wl = await workspaceRead
3042
3066
  if (!valid()) return
3043
- state.archivedIds = wl && Array.isArray(wl.archivedSessionIds) ? wl.archivedSessionIds : []
3044
- state.workspaces = wl && Array.isArray(wl.items) ? wl.items.slice() : []
3067
+ if(wl){
3068
+ state.archivedIds = Array.isArray(wl.archivedSessionIds) ? wl.archivedSessionIds : []
3069
+ state.workspaces = Array.isArray(wl.items) ? wl.items.slice() : []
3070
+ }
3045
3071
  if (!wb) { renderWorkbench(); renderSessions(); return }
3046
3072
  if (!wb.bound) {
3047
3073
  state.wb = { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false }
@@ -3052,9 +3078,9 @@ async function refreshWorkbench({ silent = false } = {}) {
3052
3078
  state.wb.bound = true
3053
3079
  state.wb.path = wb.path || ''
3054
3080
  state.wb.title = wb.title || ''
3055
- if (!wl) { state.wb.projects = []; renderWorkbench(); renderSessions(); return }
3081
+ if (!wl) { renderWorkbench(); renderSessions(); return }
3056
3082
  const items = Array.isArray(wl.items) ? wl.items.slice() : []
3057
- try {
3083
+ if (discover) try {
3058
3084
  const listRes = await fetch(fsApiUrl('/list', { path: state.wb.path }), { headers: fsHeaders() })
3059
3085
  if (!valid()) return
3060
3086
  if (listRes.ok) {
@@ -3174,6 +3200,7 @@ async function openNewSessionModal() {
3174
3200
  if (!state.token) return showView('view-settings')
3175
3201
  if (!workspaceItems().length) await refreshWorkbench({ silent: true })
3176
3202
  renderNewSessionWorkspace(LS.get('lastNewSessionWorkspaceV1', ''))
3203
+ if (workspaceItems().length === 1) return createSessionInWorkspace()
3177
3204
  $('modal-new-session').classList.remove('hidden')
3178
3205
  setTimeout(() => $('new-session-workspace')?.focus(), 50)
3179
3206
  }
@@ -3191,9 +3218,12 @@ async function createSessionInWorkspace() {
3191
3218
  if (!connection.valid() || !value?.sessionId) return
3192
3219
  LS.set('lastNewSessionWorkspaceV1', workspaceId)
3193
3220
  closeNewSessionModal()
3194
- await refreshSessions()
3195
- if (!connection.valid()) return
3196
- openSession(value.sessionId)
3221
+ const workspace = workspaceById(workspaceId)
3222
+ const session = { sessionId: value.sessionId, cwd: workspace?.path || '', running: false, projections: { values: {} } }
3223
+ state.byId.set(session.sessionId, session)
3224
+ state.sessions.unshift(session)
3225
+ void openSession(session.sessionId)
3226
+ void refreshSessions()
3197
3227
  } finally {
3198
3228
  createSessionInWorkspace.busy = false
3199
3229
  button.disabled = false
@@ -3431,6 +3461,7 @@ window.addEventListener('offline',()=>startOverviewDetection(true))
3431
3461
  document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}})
3432
3462
 
3433
3463
  function renderOverviewDesktop() {
3464
+ window.DshWorkflow?.update()
3434
3465
  const ring = $('ds-overview-pulse-ring')
3435
3466
  if (!ring) return
3436
3467
  const checks = overviewChecks()
@@ -3467,7 +3498,7 @@ function renderOverviewDesktop() {
3467
3498
  ...state.questions.map(q => ({ kind: 'question', item: q }))
3468
3499
  ]
3469
3500
  $('ds-overview-attention-count').textContent = pending.length ? t('ds.pendingCount', { n: pending.length }) : '—'
3470
- $('ds-overview-attention-list').innerHTML = pending.length ? pending.slice(0, 4).map(({ kind, item }) => {
3501
+ $('ds-overview-attention-list').innerHTML = pending.length ? pending.map(({ kind, item }) => {
3471
3502
  const title = sessionLabelOf(state.byId.get(item.sessionId))
3472
3503
  if (kind === 'approval') return `<div class="ds-overview-attention-item" data-ds-overview-approval="${esc(item.approvalId)}">
3473
3504
  <span class="ds-overview-mark">⌁</span><span class="ds-overview-copy"><span class="ds-overview-item-title">${esc(item.toolName || t('ds.toolDefault'))}</span><span class="ds-overview-item-desc">${esc(desktopApprovalDetail(item))} · ${esc(title)}</span></span>
@@ -3538,9 +3569,12 @@ function openDesktopPlugins(route = 'manage') {
3538
3569
  }
3539
3570
 
3540
3571
  function showView(id) {
3572
+ window.DshWorkflow?.close()
3573
+ if (window.DshWorkflow?.isMounted() && id === 'view-overview') id = 'view-sessions'
3541
3574
  if (id !== 'view-chat') conversationView?.pause()
3542
3575
  if (state.view === 'view-chat' && id !== 'view-chat' && state.current) void archiveEmptySessionOnLeave(state.current)
3543
3576
  state.view = id
3577
+ document.body?.classList.toggle('workflow-at-start', !!window.DshWorkflow?.isMounted() && id === 'view-sessions')
3544
3578
  for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
3545
3579
  if (id === 'view-chat') conversationView?.resume()
3546
3580
  document.querySelectorAll('.ds-nav-item').forEach(b => b.classList.toggle('active', b.dataset.view === id))
@@ -3757,7 +3791,11 @@ function bindUi() {
3757
3791
  if (!e.target.closest('#model-menu') && !e.target.closest('#btn-model')) $('model-menu')?.classList.add('hidden')
3758
3792
  })
3759
3793
  $('btn-stats-top').addEventListener('click', toggleStatsDrawer)
3760
- window.DshChatFiles?.bind($('history'), () => { const c=captureConnection(); return { ...c,sessionId:state.current,cwd:sessionCwd(state.byId.get(state.current)),native:false,headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast } })
3794
+ for (const id of ['history', 'question-body']) window.DshChatFiles?.bind($(id), () => {
3795
+ const c=captureConnection(),sessionId=id==='history'?state.current:state.questionModal?.sessionId
3796
+ return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:false,headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,preview:(path,name)=>window.DshWorkflow?.preview({...c,headers:{authorization:'Bearer '+c.token}},path,name),
3797
+ valid:()=>c.valid()&&sessionId===(id==='history'?state.current:state.questionModal?.sessionId) }
3798
+ })
3761
3799
  $('btn-insights').addEventListener('click', () => openInsights())
3762
3800
  $('stats-drawer-close').addEventListener('click', toggleStatsDrawer)
3763
3801
  // 赞赏支持
@@ -3898,7 +3936,7 @@ async function start() {
3898
3936
  }
3899
3937
  loadServers()
3900
3938
  renderServers()
3901
- showView('view-overview')
3939
+ showView(window.DshWorkflow?.isMounted() ? 'view-sessions' : 'view-overview')
3902
3940
  if (urlToken) {
3903
3941
  state.token = urlToken
3904
3942
  const currentId = state.groupActive[state.activeGroup]
@@ -3925,3 +3963,42 @@ async function start() {
3925
3963
  }
3926
3964
 
3927
3965
  start()
3966
+ mountWorkflowDesktop()
3967
+
3968
+ function mountWorkflowDesktop() {
3969
+ window.DshWorkflow?.mount({
3970
+ desktop:true, start:()=>{if(state.view==='view-overview')showView('view-sessions')},
3971
+ snapshot:()=>({token:!!state.token,host:currentServerEntry()?.note || state.server || location.host,
3972
+ gateway:activeGatewayHealth()?.ok || !!state.streamsOk?.mux,dsh:dshReachable(),
3973
+ mux:!!state.streamsOk?.mux,hostEvents:!!state.streamsOk?.host,pending:state.approvals.length+state.questions.length,
3974
+ busy:!!state.byId.get(state.current)?.running,sending:sendMessage.pending?.has(state.history)}),
3975
+ settings:name=>{showView('view-settings');showSettingsPage(name)},plugins:()=>showView('view-plugins'),
3976
+ feedback:openFeedbackModal,
3977
+ browse:()=>{closeNewSessionModal();showView('view-files')},
3978
+ register:async()=>{
3979
+ const connection=captureConnection(),path=state.fs.path;if(!path)return toast('请先选择主机目录','err')
3980
+ try{const value=await rpc('workspace.create',{path});if(!connection.valid()||!value?.workspace)return
3981
+ state.workspaces=[...state.workspaces.filter(w=>w.workspaceId!==value.workspace.workspaceId),value.workspace]
3982
+ closeWorkspaceModal();renderNewSessionWorkspace(value.workspace.workspaceId);await createSessionInWorkspace()
3983
+ }catch(error){if(connection.valid())toast(error.message,'err')}
3984
+ },
3985
+ command:runSlashCommand,send:sendMessage,refresh:refreshSessions,retry:()=>{startOverviewDetection(true);void refreshSessions()},
3986
+ operations:()=>{const connection=captureConnection();return {url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid}},
3987
+ discover:()=>{if(confirm('登记当前绑定目录下的子目录为工作区?'))void refreshWorkbench({discover:true})},
3988
+ files:()=>{const cwd=sessionCwd(state.byId.get(state.current));if(!cwd)return toast('当前会话没有工作目录','err');state.fs.loaded=true;showView('view-files');void loadFs(cwd,true)},
3989
+ admin:()=>window.open(new URL(apiUrl('/admin/'),location.href).href,'_blank','noopener,noreferrer'),
3990
+ clear:async kind=>{
3991
+ const text=kind==='history'?'清除本机历史缓存?主机记录保留。':kind==='connection'?'移除当前地址和保存的凭证?其他连接条目保留。':'清除本机全部 Remote 配置与凭证?主机数据保留。'
3992
+ if(!confirm(text))return
3993
+ clearTimeout(scheduleHistoryCacheSave._t)
3994
+ if(kind==='connection'){
3995
+ const current=currentServerEntry();if(current)state.servers=state.servers.filter(s=>s.id!==current.id)
3996
+ state.groupActive[state.activeGroup]='';state.token='';state.server='';LS.del('token');LS.del('server');saveServers()
3997
+ closeStream('mux');closeStream('host');stopPolling();renderServers();showView('view-settings');showSettingsPage('servers');return
3998
+ }
3999
+ await window.DshHistory.cacheClear()
4000
+ if(kind==='all'){window.DshWorkflow.clearStorage();location.reload()}else toast('历史缓存已清除','ok')
4001
+ },
4002
+ recover:(row,receipt)=>{const value=receipt.result?.result?.value;if(row.method==='session.create'&&value?.sessionId)void openSession(value.sessionId);if(row.sessionId===state.current)void resyncCurrentSession()},
4003
+ })
4004
+ }
package/public/index.html CHANGED
@@ -7,7 +7,7 @@
7
7
  <meta name="mobile-web-app-capable" content="yes">
8
8
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
9
9
  <title>DSH Remote</title>
10
- <script>/* 统一入口: 桌面浏览器(宽屏且 UA 非移动)访问根地址自动切换到桌面端, 手机/窄窗口继续 App 界面 */ (function(){try{var proto=location.protocol;var ua=navigator.userAgent||'';var mobile=/Android|iPhone|iPad|iPod|Mobile|Windows Phone/i.test(ua);if((proto==='http:'||proto==='https:')&&!mobile&&window.innerWidth>=1024){var p=location.pathname;if(p==='/'||/\/index\.html$/.test(p)){location.replace('desktop/desktop.html'+location.search)}}}catch(e){}})()</script>
10
+ <script>/* 统一入口: 桌面浏览器(宽屏且 UA 非移动)访问根地址自动切换到桌面端, 手机/窄窗口继续 App 界面 */ (function(){try{if(new URLSearchParams(location.search).get('layout')==='mobile'){sessionStorage.setItem('dshRemoteLayout','mobile');return}if(sessionStorage.getItem('dshRemoteLayout')==='mobile')return;var proto=location.protocol;var ua=navigator.userAgent||'';var mobile=/Android|iPhone|iPad|iPod|Mobile|Windows Phone/i.test(ua);if((proto==='http:'||proto==='https:')&&!mobile&&window.innerWidth>=1024){var p=location.pathname;if(p==='/'||/\/index\.html$/.test(p)){location.replace('desktop/desktop.html'+location.search)}}}catch(e){}})()</script>
11
11
  <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>
12
12
  <link rel="manifest" href="manifest.webmanifest">
13
13
  <link rel="icon" href="icon.svg" type="image/svg+xml">
@@ -17,6 +17,8 @@
17
17
  <link rel="stylesheet" href="skills.css">
18
18
  <link rel="stylesheet" href="extensions.css">
19
19
  <link rel="stylesheet" href="insights.css">
20
+ <link rel="stylesheet" href="workflow.css">
21
+ <link rel="stylesheet" href="relay-settings.css">
20
22
  </head>
21
23
  <body>
22
24
  <header class="topbar">
@@ -391,6 +393,7 @@
391
393
  </div>
392
394
 
393
395
  <div id="settings-page-servers" class="settings-subpage hidden" data-motion-panel>
396
+ <div id="relay-settings"></div>
394
397
  <div class="settings-group">
395
398
  <div class="setting-row" data-settings-back style="cursor:pointer">
396
399
  <button class="mini-btn" data-i18n="settings.back">‹ 返回</button>
@@ -985,7 +988,7 @@
985
988
  'session.stop': '停止本轮', 'session.history': '对话', 'session.errorMsg': '会话出错:{msg}', 'session.recovering': '恢复会话中…', 'session.recoveryReady': '会话已恢复', 'session.recoveryFailed': '会话恢复失败', 'session.recoveryCached': '正在查看缓存历史',
986
989
  'session.confirmStop': '停止当前回合?排队中的消息不会被删除。', 'session.stopFailed': '停止失败', 'session.stopRequested': '已请求停止本轮', 'session.archive': '归档', 'session.archiveConfirm': '归档这个会话?归档后可在“显示已归档会话”中打开。', 'session.archiveFailed': '归档失败:{msg}', 'session.archived': '会话已归档', 'session.archiveTitle': '确认归档会话', 'session.archiveDesc': '归档后会话将从普通列表隐藏,但不会删除对话记录。', 'session.archiveConversation': '对话', 'session.archiveWorkspace': '工作区', 'session.archiveCancel': '取消', 'session.archiveConfirmAction': '确认归档', 'session.rename': '重命名会话', 'session.renameTitle': '重命名会话', 'session.renamePlaceholder': '输入新的会话名称', 'session.renameCancel': '取消', 'session.renameConfirm': '保存', 'session.renameEmpty': '会话名称不能为空', 'session.renameFailed': '重命名失败', 'session.renamed': '会话名称已更新',
987
990
  'notify.approvalTitle': '工具审批', 'notify.approvalBody': '{tool} 需要批准', 'notify.questionTitle': 'DSH 提问', 'notify.questionBody': '需要你回答',
988
- 'notify.permissionFailed': '通知权限申请失败:{msg}',
991
+ 'notify.permissionFailed': '通知权限申请失败:{msg}', 'notify.hostUnavailable': '此通知所属服务器已移除或令牌已变更,请重新连接后查看待处理事项',
989
992
  'history.cached': '本地缓存', 'history.syncing': '本地缓存 · 正在同步', 'history.synced': '最新记录已同步', 'history.saved': '最新记录 · 已缓存', 'history.offline': '本地记录 · 网络不可用', 'history.earlier': '加载更早的记录', 'history.loadingEarlier': '正在加载更早的记录…', 'history.latest': '回到最新', 'history.cacheFailed': '已同步 · 本地缓存未保存', 'history.loading': '加载历史…', 'history.cacheFallback': '网络不可用:显示本地缓存的历史', 'history.loadFailed': '加载历史失败:{msg}', 'history.retry': '重试',
990
993
  'history.offlineCache': '离线缓存 {n} 条', 'history.count': '{n} 条', 'history.empty': '还没有消息',
991
994
  'history.queueAndCount': '队列 {q} · 历史 {n}', 'history.countOnly': '历史 {n}',
@@ -1226,7 +1229,7 @@
1226
1229
  'session.stop': 'Stop turn', 'session.history': 'Conversation', 'session.errorMsg': 'Session error: {msg}', 'session.recovering': 'Restoring session…', 'session.recoveryReady': 'Session ready', 'session.recoveryFailed': 'Session restore failed', 'session.recoveryCached': 'Viewing cached history',
1227
1230
  'session.confirmStop': 'Stop the current turn? Queued messages will be kept.', 'session.stopFailed': 'Stop failed', 'session.stopRequested': 'Stop requested', 'session.archive': 'Archive', 'session.archiveConfirm': 'Archive this session? You can open it from “Show archived”.', 'session.archiveFailed': 'Archive failed: {msg}', 'session.archived': 'Session archived', 'session.archiveTitle': 'Confirm archive', 'session.archiveDesc': 'The session will be hidden from the normal list, but its conversation will not be deleted.', 'session.archiveConversation': 'Conversation', 'session.archiveWorkspace': 'Workspace', 'session.archiveCancel': 'Cancel', 'session.archiveConfirmAction': 'Archive session', 'session.rename': 'Rename session', 'session.renameTitle': 'Rename session', 'session.renamePlaceholder': 'Enter a new session name', 'session.renameCancel': 'Cancel', 'session.renameConfirm': 'Save', 'session.renameEmpty': 'Session name cannot be empty', 'session.renameFailed': 'Rename failed', 'session.renamed': 'Session name updated',
1228
1231
  'notify.approvalTitle': 'Tool approval', 'notify.approvalBody': '{tool} needs approval', 'notify.questionTitle': 'DSH question', 'notify.questionBody': 'Needs your answer',
1229
- 'notify.permissionFailed': 'Notification permission failed: {msg}',
1232
+ 'notify.permissionFailed': 'Notification permission failed: {msg}', 'notify.hostUnavailable': 'This notification belongs to a removed server or changed credential. Reconnect to view pending requests.',
1230
1233
  'history.cached': 'Local cache', 'history.syncing': 'Local cache · Syncing', 'history.synced': 'Latest history synced', 'history.saved': 'Latest history · Cached', 'history.offline': 'Local history · Offline', 'history.earlier': 'Load earlier history', 'history.loadingEarlier': 'Loading earlier history…', 'history.latest': 'Jump to latest', 'history.cacheFailed': 'Synced · Cache could not be saved', 'history.loading': 'Loading history…', 'history.cacheFallback': 'Network unavailable: showing cached history', 'history.loadFailed': 'Failed to load history: {msg}', 'history.retry': 'Retry',
1231
1234
  'history.offlineCache': 'Offline cache {n} items', 'history.count': '{n} items', 'history.empty': 'No messages yet',
1232
1235
  'history.queueAndCount': 'Queue {q} · History {n}', 'history.countOnly': 'History {n}',
@@ -1415,6 +1418,9 @@
1415
1418
  <script src="history.js"></script>
1416
1419
  <script src="link-check.js"></script>
1417
1420
  <script src="network.js"></script>
1421
+ <script src="operations.js"></script>
1422
+ <script src="workflow.js"></script>
1423
+ <script src="relay-settings.js"></script>
1418
1424
  <script src="app.js"></script>
1419
1425
  </body>
1420
1426
  </html>
package/public/md.js CHANGED
@@ -6,9 +6,9 @@
6
6
  * 同时支持浏览器全局 window.mdToHtml 与 Node CommonJS module.exports。
7
7
  */
8
8
  (function (root, factory) {
9
- if (typeof module === 'object' && module.exports) module.exports = factory(require('./genui.js'))
10
- else root.mdToHtml = factory(root.DshGenUi)
11
- })(typeof self !== 'undefined' ? self : this, function (genui) {
9
+ if (typeof module === 'object' && module.exports) module.exports = factory(require('./genui.js'), require('./chat-files.js'))
10
+ else root.mdToHtml = factory(root.DshGenUi, root.DshChatFiles)
11
+ })(typeof self !== 'undefined' ? self : this, function (genui, files) {
12
12
  'use strict'
13
13
 
14
14
  function escapeHtml(s) {
@@ -27,10 +27,17 @@
27
27
  s = s.replace(/`([^`]+)`/g, '<code>$1</code>')
28
28
  s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
29
29
  s = s.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>')
30
- s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, function (m, text, url) {
30
+ s = s.replace(/\[([^\]]+)\]\(([^)\n]+)\)/g, function (m, text, url) {
31
31
  url = url.trim()
32
- if (fileLinks && /^(?:\.{1,2}[\\/]|file:\/\/\/|[a-z]:[\\/]|\/(?!\/))/i.test(url)) return '<a href="#" data-dsh-file-path="' + url + '">' + text + '</a>'
33
- if (!/^https?:\/\//i.test(url)) return m
32
+ if (url.startsWith('&lt;') && url.endsWith('&gt;')) url = url.slice(4, -4)
33
+ let path
34
+ const entities = { '&amp;': '&', '&quot;': '"', '&#39;': "'", '&lt;': '<', '&gt;': '>' }
35
+ try {
36
+ const raw = url.replace(/&(?:amp|quot|lt|gt);|&#39;/g, entity => entities[entity])
37
+ path = /^file:/i.test(raw) ? files?.pathOf(raw) : decodeURIComponent(raw)
38
+ } catch { return m }
39
+ if (fileLinks && (files?.pathOf(path) || files?.relativePath(path))) return '<a href="#" data-dsh-file-path="' + escapeHtml(path) + '">' + text + '</a>'
40
+ if (!/^https?:\/\//i.test(url) || /\s/.test(url)) return m
34
41
  return '<a href="' + url + '" target="_blank" rel="noopener noreferrer">' + text + '</a>'
35
42
  })
36
43
  return s
@@ -175,7 +182,7 @@
175
182
  if (code.slice(-1) === '\n') code = code.slice(0, -1)
176
183
  var fence = code.match(/^([^\n]*)\n([\s\S]*)$/)
177
184
  // Wait for the closing fence: streaming partial JSON stays readable as source.
178
- if (genui && fence && i < parts.length - 1 && fence[2].length <= 200000) {
185
+ if (options?.richContent !== false && genui && fence && i < parts.length - 1 && fence[2].length <= 200000) {
179
186
  var language = fence[1].trim().toLowerCase()
180
187
  try {
181
188
  if (/^(?:dsh-ui|json dsh-ui|dsh-ui json)$/.test(language)) {