dsh-remote-plugin 0.7.3 → 0.7.5

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.
@@ -0,0 +1 @@
1
+ .ext-page{min-width:0;width:100%;padding:16px;color:var(--dsr-text)}.ext-page.is-manage{padding:0}.ext-header{display:flex;gap:14px;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap}.ext-host{min-width:0;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dsr-muted);font-size:13px;line-height:1.7}.ext-header button{flex-shrink:0;white-space:nowrap;color:var(--dsr-text);background:var(--dsr-panel);border:1px solid var(--dsr-line);border-radius:12px;font:inherit;min-height:44px;padding:10px 14px;cursor:pointer}.ext-header button:focus-visible{outline:2px solid var(--dsr-accent);outline-offset:3px}.ext-page [hidden]{display:none!important}@media(max-width:620px){.ext-page{padding:8px 0}.ext-header{margin-bottom:18px}}
@@ -0,0 +1,103 @@
1
+ /* Optional plugin views. Entry points belong to installed plugins and session actions. */
2
+ 'use strict';
3
+ window.DshExtensions = (() => {
4
+ let current, cache
5
+ const catalog = [
6
+ { id: 'skills', name: '@linxin666/dsh-client-ui-skill-explorer', label: '打开技能中心' },
7
+ { id: 'cost', name: 'dsh-cost-meter', label: '查看费用与额度' },
8
+ { id: 'context', name: 'dsh-context', label: '查看当前会话上下文', session: true },
9
+ ]
10
+ const empty = () => ({ known: false, skills: false, cost: false, context: false })
11
+ function capabilitiesOf(snapshot) {
12
+ if (snapshot?.ok !== true || !Array.isArray(snapshot.items) || !Array.isArray(snapshot.runtime)) return empty()
13
+ const result = { ...empty(), known: true }
14
+ for (const feature of catalog) {
15
+ const item = snapshot.items.find(row => row?.name === feature.name)
16
+ if (item?.enabled !== true || snapshot.runtimeAvailable !== true) continue
17
+ if (item.runtime != null && !Array.isArray(item.runtime)) continue
18
+ const runtime = [...(item.runtime || []), ...snapshot.runtime.filter(row => row?.name === feature.name)]
19
+ result[feature.id] = runtime.length > 0 && runtime.every(row => row && row.enabled !== false && row.phase === 'active')
20
+ }
21
+ return result
22
+ }
23
+ function featuresFor(snapshot, item, session = false) {
24
+ const available = capabilitiesOf(snapshot)
25
+ return catalog.filter(feature => feature.name === item.name && available[feature.id] && (!feature.session || session))
26
+ }
27
+ function identity(config) { return config.connection || config }
28
+ function same(config) {
29
+ const next = identity(config)
30
+ return cache && cache.connection.valid() && next.valid() && cache.connection.server === next.server && cache.connection.token === next.token
31
+ }
32
+ function remember(config, snapshot) {
33
+ if (!config.valid()) return
34
+ if (!same(config)) { cache?.controller?.abort(); cache = { connection: identity(config) } }
35
+ cache.value = capabilitiesOf(snapshot); cache.at = Date.now()
36
+ cache.serial = (cache.serial || 0) + 1
37
+ }
38
+ function invalidateCapabilities() { cache?.controller?.abort(); cache = null }
39
+ async function getCapabilities(config) {
40
+ if (!config.valid()) return empty()
41
+ if (!same(config)) { invalidateCapabilities(); cache = { connection: identity(config) } }
42
+ const record = cache
43
+ if (record.value && Date.now() - record.at < 15000) return record.value
44
+ if (record.task) return record.task
45
+ record.controller = new AbortController()
46
+ const serial = record.serial || 0
47
+ record.task = (async () => {
48
+ try {
49
+ const response = await fetch(config.url('/remote/api/plugins/state'), { headers: config.headers,
50
+ signal: AbortSignal.any([record.controller.signal, AbortSignal.timeout(15000)]) })
51
+ const body = await response.text()
52
+ if (body.length > 2 * 1024 * 1024) return empty()
53
+ const snapshot = JSON.parse(body)
54
+ if (!response.ok || !config.valid() || cache !== record || snapshot?.ok !== true) return empty()
55
+ if ((record.serial || 0) !== serial) return record.value || empty()
56
+ record.value = capabilitiesOf(snapshot); record.at = Date.now(); return record.value
57
+ } catch {
58
+ if (cache === record && config.valid() && (record.serial || 0) !== serial) return record.value || empty()
59
+ if (cache === record) { record.value = empty(); record.at = Date.now() }
60
+ return empty()
61
+ }
62
+ finally { record.task = null }
63
+ })()
64
+ return record.task
65
+ }
66
+ const node=(tag,text,cls)=>{const el=document.createElement(tag);if(text!=null)el.textContent=text;if(cls)el.className=cls;return el}
67
+ const stopViews=()=>{window.DshSkillsCenter?.close();window.DshInsights?.close()}
68
+ function close(){if(current){const old=current;current=null;stopViews();window.DshPluginCenter?.close();old.target.replaceChildren()}}
69
+ function mount(config,target,initial='manage') {
70
+ close()
71
+ const s={config,target,route:'manage',navigation:0};current=s
72
+ const valid=()=>current===s&&config.valid()
73
+ const root=node('section',null,'ext-page'),header=node('header',null,'ext-header'),back=node('button','← 返回插件列表'),hint=node('p',null,'ext-host'),content=node('div',null,'ext-content'),manager=node('div',null,'ext-manager'),view=node('div',null,'ext-view')
74
+ back.type='button';header.append(back,hint);content.append(manager,view);root.append(header,content);target.replaceChildren(root)
75
+ try{hint.textContent='当前主机 · '+new URL(config.connection.server).host}catch{hint.textContent='当前连接的主机'}
76
+ async function navigate(route) {
77
+ if(!valid())return
78
+ const navigation=++s.navigation
79
+ if(route==='home')route='manage'
80
+ if(route==='context'){config.openContext?.();return}
81
+ if(route!=='manage'){
82
+ const available=await getCapabilities(config)
83
+ if(!valid()||navigation!==s.navigation)return
84
+ if(!available[route]){navigate('manage');return}
85
+ if(s.route==='manage'){s.scroller=scrollParent(root);s.scroll=s.scroller?.scrollTop||0;window.DshPluginCenter?.pause()}
86
+ }
87
+ stopViews();s.route=route;view.replaceChildren();header.hidden=route==='manage';manager.hidden=route!=='manage';view.hidden=route==='manage';root.className='ext-page'+(route==='manage'?' is-manage':'')
88
+ if(route==='manage'){
89
+ if(!s.mounted){s.mounted=true;await window.DshPluginCenter.mount({...config,onFeature:navigate},manager)}
90
+ else {if(s.scroller)s.scroller.scrollTop=s.scroll;void window.DshPluginCenter.resume()}
91
+ }else if(route==='skills')await window.DshSkillsCenter.mount(config,view,{dedicated:true})
92
+ else window.DshInsights.mount({tab:'cost',hostOverview:true,allowedTabs:['cost'],connection:config.connection,url:config.url},view)
93
+ if(valid()&&route!=='manage')config.scrollTop?.()
94
+ }
95
+ back.addEventListener('click',()=>{if(valid())void navigate('manage')})
96
+ void navigate('manage').then(()=>{if(initial!=='manage'&&initial!=='home'&&valid())void navigate(initial)})
97
+ }
98
+ function scrollParent(el) {
99
+ for(let parent=el.parentElement;parent;parent=parent.parentElement)if(parent.scrollHeight>parent.clientHeight&&/auto|scroll/.test(getComputedStyle(parent).overflowY))return parent
100
+ return document.scrollingElement
101
+ }
102
+ return {mount,close,capabilitiesOf,featuresFor,getCapabilities,remember,invalidateCapabilities}
103
+ })()
package/public/history.js CHANGED
@@ -15,6 +15,13 @@
15
15
  }
16
16
  return [...next.values()].sort((a,b) => a.seq-b.seq)
17
17
  }
18
+ function insertSorted(entries, entry) {
19
+ if (!entries.length || entries[entries.length-1].seq < entry.seq) { entries.push(entry); return }
20
+ let low=0,high=entries.length
21
+ while(low<high){const middle=(low+high)>>>1;if(entries[middle].seq<entry.seq)low=middle+1;else high=middle}
22
+ if(entries[low]?.seq===entry.seq)entries[low]=entry
23
+ else entries.splice(low,0,entry)
24
+ }
18
25
  class HistoryView {
19
26
  constructor(box, options) {
20
27
  this.box=box; this.options=options; this.entries=[]; this.start=0; this.end=0; this.nodes=new Map(); this.reading=false; this.suppress=false; this.frame=0; this.pendingOlder=false
@@ -22,8 +29,13 @@
22
29
  this.more.addEventListener('click',()=>this.older())
23
30
  this.empty=document.createElement('div'); this.empty.className='history-empty'
24
31
  this.live=document.createElement('div'); this.live.className='history-live'
25
- const intent=()=>{this.intentUntil=Date.now()+800}
26
- for(const name of ['wheel','touchmove','pointerdown'])box.addEventListener(name,intent,{passive:true})
32
+ const intent=()=>{this.intentUntil=Date.now()+1200}
33
+ const hold=()=>{intent();this.reading=true;this.options.changed?.(this)}
34
+ box.addEventListener('wheel',event=>{intent();if(event.deltaY<0)hold()},{passive:true})
35
+ box.addEventListener('touchstart',event=>{this.touchY=event.touches?.[0]?.clientY;this.lastScrollTop=box.scrollTop},{passive:true})
36
+ box.addEventListener('touchmove',event=>{const y=event.touches?.[0]?.clientY;intent();if(y>this.touchY)hold();this.touchY=y},{passive:true})
37
+ box.addEventListener('pointerdown',()=>{this.lastScrollTop=box.scrollTop;this.intentUntil=0;this.reading=true;this.options.changed?.(this)},{passive:true})
38
+ box.addEventListener('keydown',event=>{if(['ArrowUp','PageUp','Home'].includes(event.key))hold();else if(['ArrowDown','PageDown','End'].includes(event.key))intent()})
27
39
  box.addEventListener('scroll',()=>{
28
40
  if(this.suppress || this.frame)return
29
41
  this.frame=requestAnimationFrame(()=>{this.frame=0;this.onScroll()})
@@ -34,14 +46,19 @@
34
46
  for(const node of this.box.querySelectorAll('.history-entry'))if(node.getBoundingClientRect().bottom>=top+1)return {seq:Number(node.dataset.historySeq),top:node.getBoundingClientRect().top}
35
47
  return null
36
48
  }
49
+ get unread() {return Math.max(0,this.entries.length-this.end)}
50
+ get hasPending() {return this.unread>0||(this.pendingLive||'')!==(this.liveHtml||'')}
37
51
  set(entries, {reset=false, follow=false, live='', hasMore=false, loading=false, emptyLabel=''}={}) {
38
- if(!reset&&entries.length===this.entries.length&&entries.every((entry,i)=>entry===this.entries[i])&&hasMore===this.hasMore&&loading===this.loading&&(this.end===entries.length?live:'')===this.liveHtml){this.entries=entries;this.more.disabled=loading;this.more.textContent=loading?this.options.loadingLabel():this.options.olderLabel();this.domChanged=false;this.options.changed?.(this);return}
39
- if(Date.now()<this.intentUntil)this.reading=this.box.scrollHeight-this.box.scrollTop-this.box.clientHeight>=180
52
+ if(this.paused){this.pending={entries:entries.slice(),options:{reset,follow,live,hasMore,loading,emptyLabel}};return}
53
+ this.pendingLive=live
54
+ // Reading is explicit user intent. A stream update never changes it by proximity.
55
+ if(this.reading&&!reset)live=this.liveHtml||''
56
+ if(!reset&&entries.length===this.entries.length&&entries.every((entry,i)=>entry===this.entries[i])&&hasMore===this.hasMore&&loading===this.loading&&(this.end===entries.length?live:'')===this.liveHtml){this.more.disabled=loading;this.more.textContent=loading?this.options.loadingLabel():this.options.olderLabel();this.domChanged=false;this.options.changed?.(this);return}
40
57
  const oldWidth=this.end-this.start
41
58
  const anchor=this.anchor(), oldStart=this.entries[this.start]?.seq, oldEnd=this.entries[Math.max(this.start,this.end-1)]?.seq
42
- this.entries=entries; this.hasMore=hasMore; this.loading=loading
59
+ this.entries=entries.slice(); this.hasMore=hasMore; this.loading=loading
43
60
  if(reset || !this.end){this.end=entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE);this.reading=false}
44
- else if((follow || !this.reading) && this.end>=this.previousLength){this.end=entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE)}
61
+ else if(!this.reading && this.end>=this.previousLength){this.end=entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE)}
45
62
  else {
46
63
  let start=entries.findIndex(e=>e.seq===oldStart),end=entries.findIndex(e=>e.seq===oldEnd)
47
64
  if(start<0)start=anchor?entries.findIndex(e=>e.seq===anchor.seq):0
@@ -50,7 +67,7 @@
50
67
  this.previousLength=entries.length
51
68
  this.empty.textContent=emptyLabel
52
69
  this.more.textContent=loading?this.options.loadingLabel():this.options.olderLabel();this.more.disabled=loading;this.more.hidden=this.start===0&&!hasMore
53
- this.liveHtml=this.end===entries.length?live:''
70
+ this.liveHtml=this.reading&&!reset ? this.liveHtml||'' : this.end===entries.length?live:''
54
71
  this.render(anchor,reset || (!this.reading && this.end===entries.length))
55
72
  }
56
73
  render(anchor, bottom=false) {
@@ -78,28 +95,39 @@
78
95
  else if(anchor){const current=this.nodes.get(anchor.seq)?.node;if(current?.parentNode===box)box.scrollTop+=current.getBoundingClientRect().top-anchor.top}
79
96
  const active=new Set(slice.map(entry=>entry.seq));for(const seq of this.nodes.keys())if(!active.has(seq))this.nodes.delete(seq)
80
97
  cancelAnimationFrame(this.releaseFrame);this.releaseFrame=requestAnimationFrame(()=>{this.suppress=false})
98
+ this.lastScrollTop=box.scrollTop
81
99
  this.domChanged=changed
82
100
  this.options.changed?.(this)
83
101
  }
84
102
  onScroll() {
85
103
  const box=this.box
86
- if(Date.now()<this.intentUntil)this.reading=box.scrollHeight-box.scrollTop-box.clientHeight>=180
104
+ if(Date.now()<this.intentUntil){
105
+ if(box.scrollTop<(this.lastScrollTop??box.scrollTop))this.reading=true
106
+ else if(box.scrollTop>(this.lastScrollTop??box.scrollTop)&&box.scrollHeight-box.scrollTop-box.clientHeight<=8&&this.end===this.entries.length)this.reading=false
107
+ }
108
+ this.lastScrollTop=box.scrollTop
87
109
  if(box.scrollTop<80 && Date.now()<this.intentUntil)this.older()
88
- else if(box.scrollHeight-box.scrollTop-box.clientHeight<120 && this.end<this.entries.length && Date.now()<this.intentUntil){const anchor=this.anchor();this.end=Math.min(this.entries.length,this.end+WINDOW_STEP);this.start=Math.max(0,this.end-WINDOW_SIZE);this.render(anchor)}
110
+ else if(box.scrollHeight-box.scrollTop-box.clientHeight<120 && this.end<this.entries.length && Date.now()<this.intentUntil){const anchor=this.anchor();this.end=Math.min(this.entries.length,this.end+WINDOW_STEP);this.start=Math.max(0,this.end-WINDOW_SIZE);this.liveHtml=this.end===this.entries.length?this.pendingLive||'':'';this.render(anchor)}
89
111
  this.options.scrolled?.(this)
90
112
  this.domChanged=false
91
113
  this.options.changed?.(this)
92
114
  }
93
115
  async older() {
94
116
  if(this.pendingOlder)return
95
- if(this.start>0){const anchor=this.anchor();this.start=Math.max(0,this.start-WINDOW_STEP);this.end=Math.min(this.entries.length,this.start+WINDOW_SIZE);this.reading=true;this.render(anchor);return}
117
+ if(this.start>0){const anchor=this.anchor();this.start=Math.max(0,this.start-WINDOW_STEP);this.end=Math.min(this.entries.length,this.start+WINDOW_SIZE);this.reading=true;if(this.end<this.entries.length)this.liveHtml='';this.render(anchor);return}
96
118
  if(!this.hasMore || this.loading)return
97
119
  this.reading=true
98
120
  this.pendingOlder=true
99
121
  try{await this.options.older()}finally{this.pendingOlder=false}
100
122
  }
101
- latest() {this.reading=false;this.end=this.entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE);this.liveHtml=this.options.live?.()||'';this.render(null,true)}
102
- reset() {cancelAnimationFrame(this.frame);cancelAnimationFrame(this.releaseFrame);this.frame=0;this.entries=[];this.start=this.end=this.previousLength=0;this.lastRange='';this.nodes.clear();this.reading=false;this.pendingOlder=false;this.suppress=false;this.intentUntil=0;this.box.replaceChildren()}
123
+ latest() {this.reading=false;this.intentUntil=0;this.end=this.entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE);this.liveHtml=this.options.live?.()??this.pendingLive??'';this.render(null,true)}
124
+ pause() {if(!this.paused)this.savedScroll=this.box.scrollTop;this.paused=true}
125
+ resume() {
126
+ if(!this.paused)return
127
+ this.paused=false;this.box.scrollTop=this.savedScroll||0
128
+ const pending=this.pending;this.pending=null;if(pending)this.set(pending.entries,pending.options)
129
+ }
130
+ reset() {cancelAnimationFrame(this.frame);cancelAnimationFrame(this.releaseFrame);this.frame=0;this.entries=[];this.start=this.end=this.previousLength=0;this.lastRange='';this.nodes.clear();this.reading=false;this.pendingOlder=false;this.suppress=false;this.intentUntil=0;this.pendingLive='';this.pending=null;this.paused=false;this.lastScrollTop=0;this.box.replaceChildren()}
103
131
  }
104
132
  let cacheEpoch=0
105
133
  let database
@@ -154,7 +182,7 @@
154
182
  }
155
183
  async function cacheRemove(scope,id) {const key=cacheKey(scope,id);try{localStorage.removeItem(key)}catch{};const db=await openDatabase();if(db)try{db.transaction('history','readwrite').objectStore('history').delete(key)}catch{}}
156
184
  async function cacheClear() {cacheEpoch++;try{for(const key of Object.keys(localStorage))if(key.includes(':session:')||key.endsWith(':cache-index')||/^(history|sessions)Cache/.test(key))localStorage.removeItem(key)}catch{};const db=await openDatabase();if(db)await new Promise(resolve=>{try{const tx=db.transaction('history','readwrite');tx.objectStore('history').clear();tx.oncomplete=tx.onabort=tx.onerror=()=>resolve()}catch{resolve()}})}
157
- const api={HistoryView,reconcile,signature,cacheLoad,cacheSave,cacheRemove,cacheClear,decodeLegacy,WINDOW_SIZE}
185
+ const api={HistoryView,reconcile,insertSorted,signature,cacheLoad,cacheSave,cacheRemove,cacheClear,decodeLegacy,WINDOW_SIZE}
158
186
  if(typeof module!=='undefined'&&module.exports)module.exports=api
159
187
  else root.DshHistory=api
160
- })(typeof window==='undefined'?globalThis:window)
188
+ })(typeof window==='undefined'?globalThis:window)
package/public/index.html CHANGED
@@ -14,6 +14,8 @@
14
14
  <link rel="stylesheet" href="styles.css">
15
15
  <link rel="stylesheet" href="genui.css">
16
16
  <link rel="stylesheet" href="plugin-center.css">
17
+ <link rel="stylesheet" href="skills.css">
18
+ <link rel="stylesheet" href="extensions.css">
17
19
  <link rel="stylesheet" href="insights.css">
18
20
  </head>
19
21
  <body>
@@ -749,7 +751,7 @@
749
751
  <div class="session-dialog-head"><strong id="session-actions-title" data-i18n="session.more">更多操作</strong><button type="button" data-session-dialog-close aria-label="关闭">×</button></div>
750
752
  <button id="btn-rename-session" class="icon-btn hidden" data-i18n-title="session.rename" data-i18n-aria="session.rename" data-i18n="session.rename">重命名会话</button>
751
753
  <button id="btn-stats" class="icon-btn" data-i18n-title="stats.title" data-i18n-aria="stats.title" data-i18n="stats.title">本轮统计</button>
752
- <button id="btn-insights" class="icon-btn" data-i18n-title="insights.title" data-i18n-aria="insights.title" data-i18n="insights.title">上下文与费用</button>
754
+ <button id="btn-insights" class="icon-btn hidden" data-i18n-title="insights.title" data-i18n-aria="insights.title" data-i18n="insights.title">上下文与费用</button>
753
755
 
754
756
  <button id="btn-session-info" type="button" data-i18n="session.details">会话详情</button>
755
757
  <button id="btn-archive-session" class="mini-btn hidden" data-i18n="session.archive">归档</button>
@@ -994,6 +996,8 @@
994
996
  'block.image': '图片', 'block.thinking': '🧠 思考过程', 'block.thinkingLive': '🧠 思考中…', 'block.toolCall': '工具调用', 'block.toolResult': '工具结果', 'block.unknown': '块 · {type}',
995
997
  'truncated': '…(截断)',
996
998
  'insights.title': '上下文与费用',
999
+ 'insights.contextTitle': '上下文分析',
1000
+ 'insights.costTitle': '费用与额度',
997
1001
  'stats.title': '本轮统计', 'stats.roundTitle': '本轮统计', 'stats.turnsSteps': '轮次 / 步骤',
998
1002
  'stats.llmTime': '模型耗时', 'stats.minutes': ' 分钟', 'stats.outputCache': '输出 / 缓存读',
999
1003
  'stats.ctxPressure': '上下文压力', 'stats.permission': '权限', 'stats.empty': '暂无统计数据',
@@ -1233,6 +1237,8 @@
1233
1237
  'block.image': 'Image', 'block.thinking': '🧠 Thinking', 'block.thinkingLive': '🧠 Thinking…', 'block.toolCall': 'Tool call', 'block.toolResult': 'Tool result', 'block.unknown': 'Block · {type}',
1234
1238
  'truncated': '…(truncated)',
1235
1239
  'insights.title': 'Context & costs',
1240
+ 'insights.contextTitle': 'Context analysis',
1241
+ 'insights.costTitle': 'Cost & quotas',
1236
1242
  'stats.title': 'This round', 'stats.roundTitle': 'This round', 'stats.turnsSteps': 'Turns / steps',
1237
1243
  'stats.llmTime': 'LLM time', 'stats.minutes': ' min', 'stats.outputCache': 'Output / cache read',
1238
1244
  'stats.ctxPressure': 'Context pressure', 'stats.permission': 'Permission', 'stats.empty': 'No stats yet',
@@ -1397,14 +1403,18 @@
1397
1403
  <script src="i18n.js"></script>
1398
1404
  <script src="theme.js"></script>
1399
1405
  <script src="genui.js"></script>
1406
+ <script src="chat-files.js"></script>
1400
1407
  <script src="md.js"></script>
1401
1408
  <script src="vendor/gsap/gsap.min.js"></script>
1402
1409
  <script src="motion.js"></script>
1403
1410
  <script type="module" src="morphicons-init.js"></script>
1404
1411
  <script src="plugin-center.js"></script>
1412
+ <script src="skills.js"></script>
1405
1413
  <script src="insights.js"></script>
1414
+ <script src="extensions.js"></script>
1406
1415
  <script src="history.js"></script>
1407
1416
  <script src="link-check.js"></script>
1417
+ <script src="network.js"></script>
1408
1418
  <script src="app.js"></script>
1409
1419
  </body>
1410
1420
  </html>
@@ -12,3 +12,5 @@
12
12
  @media(max-width:560px){.ins-dialog{width:100%;max-width:100%;height:88dvh;max-height:88dvh;margin:auto 0 0;border-radius:20px 20px 0 0;border-bottom:0}.ins-header{padding:20px 18px 14px}.ins-tabs{padding:0 18px 14px;gap:6px}.ins-tabs button{padding:8px 12px;font-size:13px}.ins-content{padding:16px 14px max(20px,env(safe-area-inset-bottom))}.ins-section{padding:16px}.ins-metric strong{font-size:20px}.ins-category{grid-template-columns:76px minmax(0,1fr) 58px;gap:8px}.ins-events li>div{flex-wrap:wrap;gap:4px}.ins-badge{font-size:9px}}
13
13
  @media(prefers-reduced-motion:reduce){.ins-dialog::backdrop{backdrop-filter:none}}
14
14
  .ins-tabs [aria-selected=true]{color:var(--dsr-on-accent,#fff)}
15
+ .ins-page{width:100%;max-height:none;border:0;box-shadow:none;background:transparent;display:flex;flex-direction:column}.ins-page .ins-header{padding:0 0 18px}.ins-page .ins-tabs{padding:0 0 16px;flex-wrap:wrap}.ins-page .ins-content{max-height:calc(100dvh - 300px);min-height:260px;padding:18px 0}.ins-page .ins-tabs select{max-width:100%;padding:10px;border:1px solid var(--dsr-line);border-radius:10px;background:var(--dsr-panel);color:var(--dsr-text)}.ins-page .ins-header h2{font-size:24px}.ins-page .ins-metrics{grid-template-columns:repeat(auto-fit,minmax(160px,1fr))}@media(max-width:620px){.ins-page .ins-content{max-height:calc(100dvh - 330px)}}
16
+ .ins-full-page{width:min(1060px,calc(100vw - 24px));max-height:94dvh;height:94dvh}.ins-full-page .ins-content{flex:1;min-height:0}.ins-full-page [data-ins-close]{font-size:14px;padding:10px 16px}.ins-full-page .ins-tabs select{color:var(--dsr-text);background:var(--dsr-panel);border:1px solid var(--dsr-line);border-radius:10px;min-height:44px;padding:8px 12px}.ins-dialog [hidden]{display:none!important}
@@ -7,9 +7,9 @@
7
7
  const categories = ['system', 'tools', 'user', 'inject', 'skill', 'assistant', 'tool']
8
8
  const labels = {
9
9
  zh: { title: '会话洞察', context: '上下文', cost: '费用与额度', close: '关闭', refresh: '刷新', loading: '正在读取…',
10
- none: '选择一个会话后查看洞察。', missing: '此主机尚未提供 dsh-context 数据。请安装并启用插件后刷新。',
10
+ none: '选择一个会话后查看洞察。', missing: '当前连接暂未提供此会话的上下文数据。',
11
11
  unavailable: '读取失败,请重试。已有概览仍可查看。', unsupported: '当前插件或 DSH 版本暂不支持此数据格式。',
12
- costMissing: '此主机尚未提供费用数据。需要启用 dsh-cost-meter,并更新主机端 Remote 插件。',
12
+ costMissing: '当前连接暂未提供费用数据,可返回插件列表查看运行状态。',
13
13
  occupancy: '上下文占用', modelName: '当前模型', estimated: '组成 Token 为插件估算;占用优先使用 DSH 官方投影。',
14
14
  system: '系统提示', tools: '工具定义', user: '用户消息', inject: '注入内容', skill: '技能', assistant: '助手消息', tool: '工具结果',
15
15
  composition: '当前组成', events: '最近上下文变化', noEvents: '尚无压缩、裁剪或注入记录。',
@@ -22,9 +22,9 @@
22
22
  error: '供应商查询失败', stale: '缓存数据', unknown: '暂无有效数据', unlimited: '不限量', reset: '重置',
23
23
  rolling: '滚动窗口', weekly: '每周', monthly: '每月', date: '主机记账日', details: '明细' },
24
24
  en: { title: 'Session insights', context: 'Context', cost: 'Cost & quotas', close: 'Close', refresh: 'Refresh', loading: 'Loading…',
25
- none: 'Select a session to view insights.', missing: 'This host has no dsh-context data. Enable the plugin, then refresh.',
25
+ none: 'Select a session to view insights.', missing: 'Context data for this session is not available on this connection.',
26
26
  unavailable: 'Could not read data. Retry; the current overview is still available.', unsupported: 'This plugin or DSH version uses an unsupported data format.',
27
- costMissing: 'Enable dsh-cost-meter and update the host Remote plugin to read costs.', occupancy: 'Context occupancy', modelName: 'Current model',
27
+ costMissing: 'Cost data is unavailable on this connection. Check its status in the installed plugins.', occupancy: 'Context occupancy', modelName: 'Current model',
28
28
  estimated: 'Composition tokens are plugin estimates; occupancy uses the DSH projection when available.',
29
29
  system: 'System prompt', tools: 'Tool definitions', user: 'User messages', inject: 'Injections', skill: 'Skills', assistant: 'Assistant', tool: 'Tool results',
30
30
  composition: 'Current composition', events: 'Recent context changes', noEvents: 'No compaction, pruning or injection records yet.',
@@ -60,7 +60,7 @@
60
60
  const value = num(percent)
61
61
  return value === null ? '' : `<div class="ins-progress" role="progressbar" aria-label="${esc(label)}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.min(value, 100)}"><span style="width:${Math.min(value, 100)}%"></span></div>`
62
62
  }
63
- function contextHtml(session, detail, detailStatus) {
63
+ function contextHtml(session, detail, detailStatus, settings = {}) {
64
64
  const values = obj(session?.projections?.values) || {}, head = contextOf(values.contextTimeline)
65
65
  // Only combine a detail with the projection revision that requested it.
66
66
  const compatible = detail && (!head || head.detailRev === detail.rev)
@@ -84,15 +84,19 @@
84
84
  html += `<section class="ins-section"><h3>${esc(t('events'))}</h3>`
85
85
  if (head?.detailRev !== undefined && !compatible) html += `<p class="ins-note">${esc(t(detailStatus === 'loading' ? 'detailsLoading' : 'detailsFailed'))}</p>`
86
86
  else if (!Array.isArray(events) || !events.length) html += `<p class="ins-note">${esc(t('noEvents'))}</p>`
87
- else html += '<ol class="ins-events">' + events.filter(row => obj(row) && ['compaction', 'prune', 'inject', 'model', 'mode'].includes(row.kind)).slice(-8).reverse().map(row => `<li><div><strong>${esc(t(row.kind))}</strong><time>${esc(time(row.time))}</time></div><span>${esc(row.name || row.sub || '')}${num(row.tokens) !== null ? ' · ' + tokens(row.tokens) + ' tokens' : ''}</span></li>`).join('') + '</ol>'
87
+ else {
88
+ const rows = events.filter(row => obj(row) && ['compaction', 'prune', 'inject', 'model', 'mode'].includes(row.kind) && (!settings.kind || row.kind === settings.kind))
89
+ if (settings.full) html += `<p class="ins-note">${lang === 'en' ? 'Host change records' : '主机提供的变化记录'} · ${rows.length}${rows.length > 500 ? (lang === 'en' ? ' · Showing latest 500' : ' · 显示最近 500 条') : ''}</p>`
90
+ html += '<ol class="ins-events">' + rows.slice(settings.full ? -500 : -8).reverse().map(row => `<li><div><strong>${esc(t(row.kind))}</strong><time>${esc(time(row.time))}</time></div><span>${esc(row.name || row.sub || '')}${num(row.tokens) !== null ? ' · ' + tokens(row.tokens) + ' tokens' : ''}</span></li>`).join('') + '</ol>'
91
+ }
88
92
  return html + `</section><p class="ins-source">${esc(t('source'))} · dsh-context / DSH</p>`
89
93
  }
90
- function costHtml(raw, phase) {
94
+ function costHtml(raw, phase, overview = false) {
91
95
  const data = costOf(raw)
92
96
  if (!data) return `<p class="ins-empty">${esc(t(phase === 'loading' ? 'loading' : phase === 'error' ? 'unavailable' : raw?.available === false ? 'costMissing' : 'unsupported'))}</p>`
93
97
  const own = data.session?.found === true ? data.session.own : null
94
98
  let html = (phase === 'error' ? `<p role="status" class="ins-note">${esc(t('unavailable'))}</p>` : '') + `<section class="ins-section"><div class="ins-section-head"><h3>${esc(t('cost'))}</h3><span class="ins-badge">dsh-cost-meter</span></div><div class="ins-metrics">
95
- ${metric(t('session'), money(own?.apiCost), own ? '' : t('sessionMissing'))}${metric(t('today'), money(data.today?.apiCost), data.day ? t('date') + ' · ' + data.day : '')}
99
+ ${overview ? '' : metric(t('session'), money(own?.apiCost), own ? '' : t('sessionMissing'))}${metric(t('today'), money(data.today?.apiCost), data.day ? t('date') + ' · ' + data.day : '')}
96
100
  ${own && num(own.cost) !== null && own.cost !== own.apiCost ? metric(t('equivalent'), money(own.cost)) : ''}
97
101
  ${num(data.session?.subagentCount) > 0 ? metric(t('subagents'), money(data.session?.subagents?.apiCost)) : ''}</div><p class="ins-note">${esc(t('estimateNote'))}</p></section>`
98
102
  if (obj(data.balance)) {
@@ -122,16 +126,19 @@
122
126
  return html + `</section><p class="ins-source">${esc(t('source'))} · dsh-cost-meter<br>${esc(t('assembled'))} · ${esc(time(data.generatedAt))}</p>`
123
127
  }
124
128
 
125
- let dialog, options, tab = 'context', generation = 0, controller, poll, debounce
129
+ let dialog, options, tab = 'context', generation = 0, controller, poll, debounce, page = false, inline = false, eventKind = '', allowedTabs = ['context','cost']
126
130
  let detail = null, detailStatus = '', cost = null, costStatus = '', detailTask = false, detailRevision
127
131
  function current() { return options?.getSession?.() }
128
- function valid(g) { return g === generation && dialog?.open && options.connection.valid() && current()?.sessionId === options.sessionId }
132
+ function valid(g) { return g === generation && dialog?.open && options.connection.valid() && (options.hostOverview || current()?.sessionId === options.sessionId) }
129
133
  function render() {
130
134
  if (!dialog?.open) return
131
135
  if (!valid(generation)) { close(); return }
132
- dialog.querySelector('.ins-content').innerHTML = tab === 'context' ? contextHtml(current(), detail, detailStatus) : costHtml(cost, costStatus)
136
+ const content = dialog.querySelector('.ins-content'), scroll = content.scrollTop
137
+ const html = tab === 'context' ? contextHtml(current(), detail, detailStatus, { full: page, kind: eventKind }) : costHtml(cost, costStatus, options.hostOverview)
138
+ if (content.innerHTML !== html) { content.innerHTML = html; content.scrollTop = scroll }
133
139
  for (const button of dialog.querySelectorAll('[data-ins-tab]')) {
134
140
  const active = button.dataset.insTab === tab
141
+ button.hidden = page || !allowedTabs.includes(button.dataset.insTab)
135
142
  button.setAttribute('aria-selected', String(active)); button.tabIndex = active ? 0 : -1
136
143
  }
137
144
  dialog.querySelector('.ins-content').setAttribute('aria-labelledby', 'ins-tab-' + tab)
@@ -182,7 +189,7 @@
182
189
  if (!valid(g) || tab !== 'cost' || costStatus === 'loading') return
183
190
  costStatus = 'loading'; render()
184
191
  try {
185
- const data = await request('/remote/api/insights/cost?sessionId=' + encodeURIComponent(options.sessionId), null, g)
192
+ const data = await request('/remote/api/insights/cost' + (options.sessionId ? '?sessionId=' + encodeURIComponent(options.sessionId) : ''), null, g)
186
193
  if (!valid(g)) return
187
194
  if (data.available === false || costOf(data)) { cost = data; costStatus = '' }
188
195
  else costStatus = 'error'
@@ -192,37 +199,57 @@
192
199
  function scheduleContext() { clearTimeout(debounce); debounce = setTimeout(() => loadContext(), 400) }
193
200
  function close() {
194
201
  generation++; controller?.abort(); clearInterval(poll); clearTimeout(debounce)
195
- if (dialog?.open) dialog.close()
202
+ const onClose = options?.onClose
203
+ if (inline) { if (dialog) { dialog.open = false; dialog.remove(); dialog = null } }
204
+ else if (dialog?.open) dialog.close()
196
205
  options = null; detail = null; cost = null; detailTask = false; detailStatus = ''; costStatus = ''
206
+ onClose?.()
197
207
  }
198
- function open(opts) {
199
- close(); options = opts; tab = opts.tab === 'cost' ? 'cost' : 'context'; lang = root.I18N?.lang === 'en' ? 'en' : 'zh'
200
- options.sessionId = current()?.sessionId
201
- if (!options.sessionId) return
208
+ function open(opts, target) {
209
+ close(); options = opts; allowedTabs = ['context','cost'].filter(value => !opts.allowedTabs || opts.allowedTabs.includes(value))
210
+ if (!allowedTabs.length) { options = null; return }
211
+ tab = allowedTabs.includes(opts.tab) ? opts.tab : allowedTabs[0]; lang = root.I18N?.lang === 'en' ? 'en' : 'zh'
212
+ inline = !!target; page = inline || opts.fullPage === true; eventKind = ''
213
+ options.sessionId = opts.hostOverview ? '' : current()?.sessionId
214
+ if (!opts.hostOverview && !options.sessionId) return
202
215
  controller = new AbortController(); detailRevision = undefined
216
+ if (target) { dialog?.remove(); dialog = document.createElement('section'); dialog.className = 'ins-dialog ins-page'; dialog.open = true; target.replaceChildren(dialog) }
203
217
  if (!dialog) {
204
218
  dialog = document.createElement('dialog'); dialog.className = 'ins-dialog'; document.body.append(dialog)
205
219
  dialog.addEventListener('cancel', event => { event.preventDefault(); close() })
206
220
  dialog.addEventListener('close', () => { if (options && !dialog.open) close() })
207
221
  }
208
- dialog.innerHTML = `<header class="ins-header"><div><h2 id="ins-title">${esc(t('title'))}</h2><p>${esc(opts.getTitle?.() || options.sessionId)}</p></div><button type="button" data-ins-close aria-label="${esc(t('close'))}">×</button></header>
222
+ if (!inline) dialog.className = 'ins-dialog' + (page ? ' ins-full-page' : '')
223
+ const title = opts.hostOverview || page && tab === 'cost' ? t('cost') : page ? (lang === 'en' ? 'Context analysis' : '上下文分析') : allowedTabs.length === 1 ? t(allowedTabs[0]) : t('title')
224
+ dialog.innerHTML = `<header class="ins-header"><div><h2 id="ins-title">${esc(title)}</h2><p>${esc(opts.hostOverview ? (lang === 'en' ? 'Current host · today, balance and plan quotas' : '当前主机 · 今日费用、账户余额与套餐额度') : opts.getTitle?.() || options.sessionId)}</p></div>${inline ? '' : `<button type="button" data-ins-close aria-label="${esc(t('close'))}">${page ? (lang === 'en' ? 'Back' : '返回') : '×'}</button>`}</header>
209
225
  <nav class="ins-tabs" role="tablist" aria-label="${esc(t('title'))}"><button type="button" role="tab" id="ins-tab-context" data-ins-tab="context" aria-controls="ins-content">${esc(t('context'))}</button><button type="button" role="tab" id="ins-tab-cost" data-ins-tab="cost" aria-controls="ins-content">${esc(t('cost'))}</button><button type="button" data-ins-refresh>${esc(t('refresh'))}</button></nav><div id="ins-content" class="ins-content" role="tabpanel" tabindex="0"></div>`
210
226
  dialog.setAttribute('aria-labelledby', 'ins-title')
211
- dialog.querySelector('[data-ins-close]').addEventListener('click', close)
212
- function select(value) { tab = value; render(); tab === 'cost' ? loadCost() : loadContext() }
227
+ if (!inline) dialog.querySelector('[data-ins-close]').addEventListener('click', close)
228
+ if (page) {
229
+ dialog.querySelectorAll('[data-ins-tab]').forEach(button => { button.hidden = true })
230
+ if (tab === 'context') {
231
+ const filter = document.createElement('select'); filter.setAttribute('aria-label', lang === 'en' ? 'Change type' : '变化类型')
232
+ filter.innerHTML = [['', lang === 'en' ? 'All changes' : '全部变化'], ...['compaction', 'prune', 'inject', 'model', 'mode'].map(kind => [kind, t(kind)])].map(([value,label]) => `<option value="${value}">${esc(label)}</option>`).join('')
233
+ filter.addEventListener('change', () => { eventKind = filter.value; render() }); dialog.querySelector('.ins-tabs').prepend(filter)
234
+ }
235
+ } else if (opts.onFullPage) {
236
+ const expand = document.createElement('button'); expand.type = 'button'; expand.textContent = lang === 'en' ? 'Open page' : '打开完整页面'
237
+ expand.addEventListener('click', () => { const selected = tab; close(); opts.onFullPage(selected) }); dialog.querySelector('.ins-tabs').append(expand)
238
+ }
239
+ function select(value) { if(!allowedTabs.includes(value))return;tab = value; render(); tab === 'cost' ? loadCost() : loadContext() }
213
240
  dialog.querySelectorAll('[data-ins-tab]').forEach(button => {
214
241
  button.addEventListener('click', () => select(button.dataset.insTab))
215
242
  button.addEventListener('keydown', event => {
216
243
  if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return
217
- event.preventDefault(); select(event.key === 'Home' ? 'context' : event.key === 'End' ? 'cost' : tab === 'context' ? 'cost' : 'context')
244
+ event.preventDefault(); select(event.key === 'Home' ? allowedTabs[0] : event.key === 'End' ? allowedTabs.at(-1) : allowedTabs[(allowedTabs.indexOf(tab)+1)%allowedTabs.length])
218
245
  dialog.querySelector('[data-ins-tab="' + tab + '"]').focus()
219
246
  })
220
247
  })
221
248
  dialog.querySelector('[data-ins-refresh]').addEventListener('click', () => tab === 'cost' ? loadCost() : loadContext(true))
222
- dialog.showModal(); render(); tab === 'cost' ? loadCost() : loadContext()
249
+ if (!inline) dialog.showModal(); render(); tab === 'cost' ? loadCost() : loadContext()
223
250
  poll = setInterval(() => { if (!valid(generation)) close(); else if (tab === 'cost') loadCost(); else { render(); loadContext() } }, 60000)
224
251
  }
225
- const api = { open, close, update() { if (dialog?.open) { render(); if (dialog.open && tab === 'context') scheduleContext() } }, contextOf, costOf, contextHtml, costHtml }
252
+ const api = { open, mount: (opts, target) => open(opts, target), close, update() { if (dialog?.open) { render(); if (dialog?.open && tab === 'context') scheduleContext() } }, contextOf, costOf, contextHtml, costHtml }
226
253
  root.DshInsights = api
227
254
  if (typeof module !== 'undefined') module.exports = api
228
255
  })(typeof window !== 'undefined' ? window : globalThis)
package/public/md.js CHANGED
@@ -23,12 +23,13 @@
23
23
  })
24
24
  }
25
25
 
26
- function inline(s) {
26
+ function inline(s, fileLinks) {
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
30
  s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/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>'
32
33
  if (!/^https?:\/\//i.test(url)) return m
33
34
  return '<a href="' + url + '" target="_blank" rel="noopener noreferrer">' + text + '</a>'
34
35
  })
@@ -81,10 +82,10 @@
81
82
  return { headers: headers, alignments: alignments, rows: rows, next: i }
82
83
  }
83
84
 
84
- function tableHtml(table) {
85
+ function tableHtml(table, fileLinks) {
85
86
  function cellTag(tag, value, align) {
86
87
  var style = align ? ' style="text-align:' + align + '"' : ''
87
- return '<' + tag + style + '>' + inline(value) + '</' + tag + '>'
88
+ return '<' + tag + style + '>' + inline(value, fileLinks) + '</' + tag + '>'
88
89
  }
89
90
  var head = '<thead><tr>' + table.headers.map(function (value, i) {
90
91
  return cellTag('th', value, table.alignments[i])
@@ -99,7 +100,7 @@
99
100
  return '<div class="md-table-wrap"><table>' + head + body + '</table></div>'
100
101
  }
101
102
 
102
- function renderLines(lines) {
103
+ function renderLines(lines, fileLinks) {
103
104
  var html = ''
104
105
  var i = 0
105
106
  while (i < lines.length) {
@@ -109,19 +110,19 @@
109
110
  var h = line.match(/^(#{1,3})\s+(.*)$/)
110
111
  if (h) {
111
112
  var level = h[1].length
112
- html += '<h' + level + '>' + inline(h[2]) + '</h' + level + '>'
113
+ html += '<h' + level + '>' + inline(h[2], fileLinks) + '</h' + level + '>'
113
114
  i++
114
115
  continue
115
116
  }
116
117
  var table = tableAt(lines, i)
117
118
  if (table) {
118
- html += tableHtml(table)
119
+ html += tableHtml(table, fileLinks)
119
120
  i = table.next
120
121
  continue
121
122
  }
122
123
  var q = line.match(/^&gt;\s?(.*)$/)
123
124
  if (q) {
124
- html += '<blockquote>' + inline(q[1]) + '</blockquote>'
125
+ html += '<blockquote>' + inline(q[1], fileLinks) + '</blockquote>'
125
126
  i++
126
127
  continue
127
128
  }
@@ -131,7 +132,7 @@
131
132
  while (i < lines.length) {
132
133
  var um = lines[i].match(/^[-*]\s+(.*)$/)
133
134
  if (!um) break
134
- items.push(inline(um[1]))
135
+ items.push(inline(um[1], fileLinks))
135
136
  i++
136
137
  }
137
138
  html += '<ul>' + items.map(function (x) { return '<li>' + x + '</li>' }).join('') + '</ul>'
@@ -143,7 +144,7 @@
143
144
  while (i < lines.length) {
144
145
  var om = lines[i].match(/^\d+[.)]\s+(.*)$/)
145
146
  if (!om) break
146
- oitems.push(inline(om[1]))
147
+ oitems.push(inline(om[1], fileLinks))
147
148
  i++
148
149
  }
149
150
  html += '<ol>' + oitems.map(function (x) { return '<li>' + x + '</li>' }).join('') + '</ol>'
@@ -155,7 +156,7 @@
155
156
  var ct = cur.trim()
156
157
  if (!ct) break
157
158
  if (/^(#{1,3})\s+/.test(cur) || /^&gt;\s?/.test(cur) || /^[-*]\s+/.test(cur) || /^\d+[.)]\s+/.test(cur)) break
158
- para.push(inline(cur))
159
+ para.push(inline(cur, fileLinks))
159
160
  i++
160
161
  }
161
162
  if (para.length) html += '<p>' + para.join('<br>') + '</p>'
@@ -163,7 +164,7 @@
163
164
  return html
164
165
  }
165
166
 
166
- function mdToHtml(text) {
167
+ function mdToHtml(text, options) {
167
168
  var raw = String(text == null ? '' : text)
168
169
  var parts = raw.split(/```/)
169
170
  var out = ''
@@ -188,7 +189,7 @@
188
189
  out += '<pre><code>' + escapeHtml(code) + '</code></pre>'
189
190
  } else {
190
191
  var escaped = escapeHtml(parts[i])
191
- out += renderLines(escaped.split('\n'))
192
+ out += renderLines(escaped.split('\n'), options?.fileLinks === true)
192
193
  }
193
194
  }
194
195
  return out