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

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,109 @@
1
+ /* Device-local operation evidence. No message bodies, uploads or dependencies. */
2
+ 'use strict'
3
+ function createDiagnosticSchema() {
4
+ const MAX_EVENTS=160,MAX_BYTES=48000
5
+ const kinds=new Set(['rpc','history.load','history.cache','history.render','history.row','session.open','session.back','stream.state','stream.retry','poll.state','client.lifecycle','client.error','feedback.submit'])
6
+ const enums={phase:['start','response','prepared','rendered','complete','failed','navigate','cleanup','hit','miss','retry'],channel:['mux','host'],status:['open','closed','connecting','poll','ws','visible','hidden','online','offline','running','stopped','starting','disabled','start-failed','timeout','error','unknown','granted','denied','default'],category:['authentication','timeout','network','render','syntax','upstream','unknown'],errorName:['Error','TypeError','RangeError','SyntaxError','ReferenceError','AbortError','TimeoutError','NetworkError']}
7
+ enums.serviceState=['starting','running','stopped','disabled','start-failed','system-timeout','auth-expired']
8
+ const numbers=['durationMs','httpStatus','closeCode','attempt','delayMs','count','rawCount','renderedCount','renderErrors','lastSuccessAt','intervalMin','apiLevel']
9
+ const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled']
10
+ const methods=new Set(['session.list','session.history','session.create','session.prompt','session.fork','session.cancel','session.rename','session.selectModel','session.updateQueue','session.getModels','session.getQueue','session.getCompactionStatus','workspace.list','workspace.create','workspace.archiveSession','host.describe','subagent.list','subagent.interrupt','goal.edit','goal.pause','goal.resume','goal.complete','goal.clear'])
11
+ for(const method of ['session.models','llm.discoverModels','llm.providers','credentials.describe','credentials.set','credentials.unset','settings.describe','settings.mutate','settings.openDocument'])methods.add(method)
12
+ const hex=(v,n)=>typeof v==='string'&&new RegExp('^[a-f0-9]{'+n+'}$').test(v)?v:undefined
13
+ const version=v=>typeof v==='string'&&/^\d+\.\d+\.\d+(?:[.-][a-zA-Z0-9.-]{1,30})?$/.test(v)?v:'unknown'
14
+ function facts(input={}) {
15
+ const out={}
16
+ for(const [key,values]of Object.entries(enums))if(values.includes(input[key]))out[key]=input[key]
17
+ for(const key of numbers)if(typeof input[key]==='number'&&Number.isFinite(input[key])&&input[key]>=0)out[key]=Math.min(input[key],Number.MAX_SAFE_INTEGER)
18
+ for(const key of booleans)if(typeof input[key]==='boolean')out[key]=input[key]
19
+ if(methods.has(input.method))out.method=input.method
20
+ for(const key of ['sessionRef','serverRef'])if(hex(input[key],16))out[key]=input[key]
21
+ if(hex(input.traceId,24))out.traceId=input.traceId
22
+ if(Array.isArray(input.frames))out.frames=input.frames.slice(0,3).filter(f=>['app.js','desktop.js','history.js','activity.js','turn-results.js','network.js','operations.js','diagnostics.js'].includes(f?.file)&&Number.isSafeInteger(f.line)&&f.line>0&&Number.isSafeInteger(f.column)&&f.column>0).map(f=>({file:f.file,line:f.line,column:f.column}))
23
+ return out
24
+ }
25
+ function sanitizeReport(input) {
26
+ if(!input||input.schema!==1||!Array.isArray(input.events))return null
27
+ const report={schema:1,reportId:hex(input.reportId,24)||'000000000000000000000000',capturedAt:typeof input.capturedAt==='number'&&Number.isFinite(input.capturedAt)?input.capturedAt:0,
28
+ client:{version:version(input.client?.version),buildId:hex(input.client?.buildId,64)||'unknown',surface:['mobile','desktop'].includes(input.client?.surface)?input.client.surface:'mobile'},
29
+ snapshot:facts(input.snapshot),events:[]}
30
+ for(const item of input.events.slice(-MAX_EVENTS))if(item&&kinds.has(item.kind)&&typeof item.at==='number'&&Number.isFinite(item.at))report.events.push({at:item.at,kind:item.kind,...facts(item)})
31
+ while(JSON.stringify(report).length>MAX_BYTES&&report.events.length)report.events.shift()
32
+ return report
33
+ }
34
+ return {MAX_EVENTS,MAX_BYTES,kinds,facts,sanitizeReport}
35
+ }
36
+ ;(function(root){
37
+ const schema=createDiagnosticSchema()
38
+ function createDiagnostics(env) {
39
+ const KEY='dshRemoteDiagnosticsV1',SALT_KEY=KEY+'Salt',MAX_AGE=86400000
40
+ let rows=[],timer,config={},metadata={},sequence=0,sheet,exportTimer
41
+ const random=()=>{const bytes=new Uint8Array(12);env.crypto?.getRandomValues?.(bytes);return [...bytes].map(n=>n.toString(16).padStart(2,'0')).join('')}
42
+ let salt=random(),run=random()
43
+ try{salt=env.localStorage.getItem(SALT_KEY)||salt;env.localStorage.setItem(SALT_KEY,salt);const saved=JSON.parse(env.localStorage.getItem(KEY)||'null');rows=schema.sanitizeReport(saved)?.events||[]}catch{}
44
+ const now=()=>Date.now()
45
+ const pseudonym=value=>{if(!value||!env.SHA256)return undefined;try{return new env.SHA256().update(new TextEncoder().encode(salt+'\0'+value)).hex().slice(0,16)}catch{return undefined}}
46
+ const trim=()=>{rows=rows.filter(row=>row.at>now()-MAX_AGE&&row.at<=now()+60000).slice(-schema.MAX_EVENTS);while(JSON.stringify(rows).length>schema.MAX_BYTES-3000)rows.shift()}
47
+ function snapshot(){let value={};try{value=config.snapshot?.()||{}}catch{};return schema.facts({...value,sessionRef:pseudonym(value.sessionId),serverRef:pseudonym(value.server||env.location?.origin),online:env.navigator?.onLine!==false})}
48
+ function report(){trim();return schema.sanitizeReport({schema:1,reportId:random(),capturedAt:now(),client:{...metadata,surface:config.surface||'mobile'},snapshot:snapshot(),events:rows})}
49
+ function flush(){if(timer)env.clearTimeout?.(timer);timer=null;try{env.localStorage.setItem(KEY,JSON.stringify(report()))}catch{}}
50
+ function record(kind,fields={}) {
51
+ if(!schema.kinds.has(kind))return
52
+ const row={at:now(),kind,...schema.facts({...fields,sessionRef:fields.sessionRef||pseudonym(fields.sessionId),serverRef:fields.serverRef||pseudonym(fields.server||env.location?.origin)})};rows.push(row);trim()
53
+ if(fields.phase==='failed'||kind==='client.error'||fields.phase==='start'&&['session.open','session.back','history.load','history.render','history.cache'].includes(kind))flush()
54
+ else if(!timer)timer=env.setTimeout?.(flush,500)
55
+ return row
56
+ }
57
+ function errorFacts(error){
58
+ const message=String(error?.message||''),category=/auth|ticket|401|403/i.test(message)?'authentication':/timeout|abort/i.test(message+' '+error?.name)?'timeout':/network|fetch|socket/i.test(message)?'network':error?.name==='SyntaxError'?'syntax':'unknown',frames=[]
59
+ for(const line of String(error?.stack||'').split('\n').slice(1,8)){const match=line.match(/(?:[/\\])(app|desktop|history|activity|turn-results|network|operations|diagnostics)\.js(?:\?[^\s:]*)?:(\d+):(\d+)\)?$/);if(match)frames.push({file:match[1]+'.js',line:Number(match[2]),column:Number(match[3])})}
60
+ return schema.facts({category,errorName:error?.name,frames,...(/^HTTP \d{3}$/.test(message)?{httpStatus:Number(message.slice(5))}:{})})
61
+ }
62
+ function start(kind,fields={}){const begun=now(),traceId=run.slice(0,12)+(++sequence).toString(16).padStart(12,'0');record(kind,{...fields,phase:'start',traceId});return {traceId,end:value=>record(kind,{...fields,...value,traceId,durationMs:now()-begun}),fail:error=>record(kind,{...fields,...errorFacts(error),phase:'failed',traceId,durationMs:now()-begun})}}
63
+ function nativeSnapshot(){try{const value=JSON.parse(env.NativeBackground?.getBackgroundConfig?.()||'{}');return schema.facts({...value,httpStatus:value.lastHttpStatus})}catch{return {}}}
64
+ function configure(value){config=value;record('client.lifecycle',{status:env.document?.visibilityState==='hidden'?'hidden':'visible',...nativeSnapshot()});mount()}
65
+ function clear(){rows=[];flush();refreshPreview()}
66
+ function text(){return JSON.stringify(report(),null,2)}
67
+ const label=(zh,en)=>env.I18N?.lang==='en'?en:zh
68
+ const $=id=>env.document?.getElementById(id)
69
+ function refreshPreview(){const node=$('fb-client-log-preview');if(node)node.textContent=text()}
70
+ function exportStatus(attempt=0){
71
+ const status=$('fb-client-log-status');let phase='error'
72
+ try{phase=env.NativeFile.getDiagnosticExportStatus()}catch{}
73
+ if(status)status.textContent=phase==='saved'?label('日志已保存','Report saved'):phase==='cancelled'?label('已取消保存','Save cancelled'):phase==='picking'?label('请在系统文件选择器中保存日志','Save the report in the system file picker'):label('导出失败,请复制日志。','Export failed. Copy the report instead.')
74
+ if(phase==='picking'&&attempt<120)exportTimer=env.setTimeout(()=>exportStatus(attempt+1),1000)
75
+ }
76
+ function download(){try{
77
+ if(env.NativeFile?.exportDiagnostics){if(!env.NativeFile.exportDiagnostics(text()))throw Error('export unavailable');if(exportTimer)env.clearTimeout(exportTimer);exportStatus();return}
78
+ if(env.NativeBackground)throw Error('native export unavailable')
79
+ const blob=new env.Blob([text()],{type:'application/json'}),url=env.URL.createObjectURL(blob),a=env.document.createElement('a');a.href=url;a.download='dsh-diagnostics-'+now()+'.json';env.document.body.append(a);a.click();a.remove();env.setTimeout(()=>env.URL.revokeObjectURL(url),1000)
80
+ }catch{const status=$('fb-client-log-status');if(status)status.textContent=label('导出失败,请复制日志。','Export failed. Copy the report instead.')}}
81
+ function show(){if(!sheet)return;const status=$('fb-client-log-status');if(status)status.textContent='';refreshPreview();$('fb-client-log-details').open=true;if(!sheet.open)sheet.showModal()}
82
+ function mount(){
83
+ const details=$('fb-client-log-details');if(!details||details.dataset.bound)return;details.dataset.bound='1'
84
+ const panel=details.closest('.client-diagnostics'),entry=env.document.createElement('button');entry.type='button';entry.className='workflow-button';entry.dataset.logLabel='entry';panel.parentNode.insertBefore(entry,panel);entry.addEventListener('click',show)
85
+ sheet=env.document.createElement('dialog');sheet.className='client-log-dialog';sheet.setAttribute('aria-labelledby','client-log-title')
86
+ const head=env.document.createElement('div');head.className='client-log-head';const title=env.document.createElement('h2');title.id='client-log-title';title.dataset.logLabel='title';const close=env.document.createElement('button');close.type='button';close.dataset.logLabel='close';close.addEventListener('click',()=>sheet.close());head.append(title,close);sheet.append(head,panel);env.document.body.append(sheet)
87
+ const labels={entry:['查看本地操作日志','View local operation logs'],title:['本地操作日志','Local operation logs'],close:['关闭','Close'],privacy:['操作日志仅保存在此设备,记录操作阶段、耗时、错误位置与连接状态。可复制或导出后自行反馈。','Operation logs stay on this device and include stages, durations, error locations and connection status. Copy or export them to share feedback yourself.'],details:['查看详细记录','View detailed records'],refresh:['刷新预览','Refresh preview'],copy:['复制日志','Copy report'],export:['导出日志','Export report'],clear:['清除日志','Clear report']}
88
+ const translate=()=>{for(const node of env.document.querySelectorAll('[data-log-label]')){const pair=labels[node.dataset.logLabel];if(pair)node.textContent=label(...pair)}}
89
+ translate();if(env.MutationObserver)new env.MutationObserver(translate).observe(env.document.documentElement,{attributes:true,attributeFilter:['lang']})
90
+ details.addEventListener('toggle',()=>{if(details.open)refreshPreview()})
91
+ $('fb-log-preview')?.addEventListener('click',refreshPreview)
92
+ $('fb-log-copy')?.addEventListener('click',async()=>{const status=$('fb-client-log-status');let ok=false;try{ok=!!await config.copy?.(text())}catch{};if(status)status.textContent=ok?label('已复制脱敏日志','Report copied'):label('复制失败,请导出日志。','Copy failed. Export the report instead.')})
93
+ $('fb-log-export')?.addEventListener('click',download)
94
+ $('fb-log-clear')?.addEventListener('click',clear)
95
+ }
96
+ env.addEventListener?.('error',event=>record('client.error',{...errorFacts(event.error),phase:'failed'}))
97
+ env.addEventListener?.('unhandledrejection',event=>record('client.error',{...errorFacts(event.reason),phase:'failed'}))
98
+ for(const status of ['online','offline'])env.addEventListener?.(status,()=>record('client.lifecycle',{status,online:status==='online'}))
99
+ env.document?.addEventListener('visibilitychange',()=>{record('client.lifecycle',{status:env.document.visibilityState==='visible'?'visible':'hidden',...nativeSnapshot()});flush()})
100
+ env.addEventListener?.('pagehide',flush)
101
+ function build(value){metadata={version:value?.version,buildId:value?.buildId}}
102
+ return {record,start,errorFacts,report,text,flush,clear,configure,show,download,build,nativeSnapshot}
103
+ }
104
+ if(typeof module!=='undefined'&&module.exports)module.exports={createDiagnostics,createDiagnosticSchema}
105
+ else {
106
+ root.DshDiagnostics=createDiagnostics(root)
107
+ try{const url=new URL('build.json',root.document.currentScript.src);void root.fetch(url,{cache:'no-store',signal:AbortSignal.timeout(5000)}).then(r=>r.ok?r.json():{}).then(value=>root.DshDiagnostics.build(value)).catch(()=>{})}catch{}
108
+ }
109
+ })(typeof window==='undefined'?globalThis:window)
@@ -4,10 +4,11 @@ window.DshExtensions = (() => {
4
4
  let current, cache
5
5
  const catalog = [
6
6
  { id: 'skills', name: '@linxin666/dsh-client-ui-skill-explorer', label: '打开技能中心' },
7
+ { id: 'teams', name: '@nanmicoder/dsh-agent-teams', label: '查看智能体团队' },
7
8
  { id: 'cost', name: 'dsh-cost-meter', label: '查看费用与额度' },
8
9
  { id: 'context', name: 'dsh-context', label: '查看当前会话上下文', session: true },
9
10
  ]
10
- const empty = () => ({ known: false, skills: false, cost: false, context: false })
11
+ const empty = () => ({ known: false, skills: false, cost: false, context: false, teams: false })
11
12
  function capabilitiesOf(snapshot) {
12
13
  if (snapshot?.ok !== true || !Array.isArray(snapshot.items) || !Array.isArray(snapshot.runtime)) return empty()
13
14
  const result = { ...empty(), known: true }
@@ -64,7 +65,7 @@ window.DshExtensions = (() => {
64
65
  return record.task
65
66
  }
66
67
  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
+ const stopViews=()=>{window.DshSkillsCenter?.close();window.DshInsights?.close();window.DshTeams?.close()}
68
69
  function close(){if(current){const old=current;current=null;stopViews();window.DshPluginCenter?.close();old.target.replaceChildren()}}
69
70
  function mount(config,target,initial='manage') {
70
71
  close()
@@ -84,15 +85,17 @@ window.DshExtensions = (() => {
84
85
  if(!available[route]){navigate('manage');return}
85
86
  if(s.route==='manage'){s.scroller=scrollParent(root);s.scroll=s.scroller?.scrollTop||0;window.DshPluginCenter?.pause()}
86
87
  }
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
+ stopViews();s.route=route;view.replaceChildren();header.hidden=route==='manage'&&!config.back;manager.hidden=route!=='manage';view.hidden=route==='manage';root.className='ext-page'+(route==='manage'?' is-manage':'')
89
+ back.textContent=route==='manage'?(window.I18N?.lang==='en'?'← Back to More':'← 返回更多'):(window.I18N?.lang==='en'?'← Back to plugins':'← 返回插件列表')
88
90
  if(route==='manage'){
89
91
  if(!s.mounted){s.mounted=true;await window.DshPluginCenter.mount({...config,onFeature:navigate},manager)}
90
92
  else {if(s.scroller)s.scroller.scrollTop=s.scroll;void window.DshPluginCenter.resume()}
91
93
  }else if(route==='skills')await window.DshSkillsCenter.mount(config,view,{dedicated:true})
94
+ else if(route==='teams')await window.DshTeams.mount(config,view)
92
95
  else window.DshInsights.mount({tab:'cost',hostOverview:true,allowedTabs:['cost'],connection:config.connection,url:config.url},view)
93
96
  if(valid()&&route!=='manage')config.scrollTop?.()
94
97
  }
95
- back.addEventListener('click',()=>{if(valid())void navigate('manage')})
98
+ back.addEventListener('click',()=>{if(valid()){if(s.route==='manage')config.back?.();else void navigate('manage')}})
96
99
  void navigate('manage').then(()=>{if(initial!=='manage'&&initial!=='home'&&valid())void navigate(initial)})
97
100
  }
98
101
  function scrollParent(el) {
package/public/history.js CHANGED
@@ -24,17 +24,22 @@
24
24
  }
25
25
  class HistoryView {
26
26
  constructor(box, options) {
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
27
+ this.box=box; this.options=options; this.entries=[]; this.start=0; this.end=0; this.nodes=new Map(); this.disclosures=new Map(); this.reading=false; this.suppress=false; this.frame=0; this.pendingOlder=false
28
28
  this.more=document.createElement('button'); this.more.type='button'; this.more.className='history-page-control'; this.more.textContent=options.olderLabel()
29
29
  this.more.addEventListener('click',()=>this.older())
30
30
  this.empty=document.createElement('div'); this.empty.className='history-empty'
31
+ this.retry=document.createElement('button');this.retry.type='button';this.retry.className='history-page-control';this.retry.textContent=options.retryLabel?.()||'Retry'
32
+ this.retry.addEventListener('click',()=>options.retry?.())
31
33
  this.live=document.createElement('div'); this.live.className='history-live'
34
+ box.addEventListener('toggle',event=>{const detail=event.target;if(detail?.dataset?.activityKey)this.rememberDisclosure(detail)},true)
32
35
  const intent=()=>{this.intentUntil=Date.now()+1200}
33
36
  const hold=()=>{intent();this.reading=true;this.options.changed?.(this)}
34
37
  box.addEventListener('wheel',event=>{intent();if(event.deltaY<0)hold()},{passive:true})
35
38
  box.addEventListener('touchstart',event=>{this.touchY=event.touches?.[0]?.clientY;this.lastScrollTop=box.scrollTop},{passive:true})
36
39
  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})
40
+ // Pressing a card or selecting text pauses following, but only when actually
41
+ // scrolled away from the tail: tapping at the bottom must not fake "new content".
42
+ box.addEventListener('pointerdown',()=>{this.lastScrollTop=box.scrollTop;this.intentUntil=0;if(!this.atBottom)this.reading=true;this.options.changed?.(this)},{passive:true})
38
43
  box.addEventListener('keydown',event=>{if(['ArrowUp','PageUp','Home'].includes(event.key))hold();else if(['ArrowDown','PageDown','End'].includes(event.key))intent()})
39
44
  box.addEventListener('scroll',()=>{
40
45
  if(this.suppress || this.frame)return
@@ -48,12 +53,18 @@
48
53
  }
49
54
  get unread() {return Math.max(0,this.entries.length-this.end)}
50
55
  get hasPending() {return this.unread>0||(this.pendingLive||'')!==(this.liveHtml||'')}
56
+ /** Real viewport position, not an intent flag: a stale `reading` must never keep the jump button up at the bottom. */
57
+ get atBottom() {const box=this.box;return box.scrollHeight-box.scrollTop-box.clientHeight<=24}
51
58
  set(entries, {reset=false, follow=false, live='', hasMore=false, loading=false, emptyLabel=''}={}) {
52
59
  if(this.paused){this.pending={entries:entries.slice(),options:{reset,follow,live,hasMore,loading,emptyLabel}};return}
60
+ // A stale flag is cleaned up only when no gesture is in progress: while the user is
61
+ // actively scrolling up from the bottom a stream update must not clear `reading`,
62
+ // otherwise every chunk snaps the view back to the tail.
63
+ if(this.reading&&Date.now()>(this.intentUntil||0)&&this.atBottom&&this.end>=this.entries.length)this.reading=false
53
64
  this.pendingLive=live
54
65
  // Reading is explicit user intent. A stream update never changes it by proximity.
55
66
  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}
67
+ if(!reset&&!this.renderErrors&&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}
57
68
  const oldWidth=this.end-this.start
58
69
  const anchor=this.anchor(), oldStart=this.entries[this.start]?.seq, oldEnd=this.entries[Math.max(this.start,this.end-1)]?.seq
59
70
  this.entries=entries.slice(); this.hasMore=hasMore; this.loading=loading
@@ -65,31 +76,47 @@
65
76
  this.start=Math.max(0,start-(this.pendingOlder?WINDOW_STEP:0));this.end=Math.min(entries.length,Math.max(this.start+1,end+1,this.start+Math.min(WINDOW_SIZE,oldWidth)))
66
77
  }
67
78
  this.previousLength=entries.length
68
- this.empty.textContent=emptyLabel
79
+ this.emptyLabel=emptyLabel
69
80
  this.more.textContent=loading?this.options.loadingLabel():this.options.olderLabel();this.more.disabled=loading;this.more.hidden=this.start===0&&!hasMore
70
81
  this.liveHtml=this.reading&&!reset ? this.liveHtml||'' : this.end===entries.length?live:''
71
82
  this.render(anchor,reset || (!this.reading && this.end===entries.length))
72
83
  }
84
+ rememberDisclosure(detail) {
85
+ const key=detail.dataset.activityKey;if(!key)return
86
+ this.disclosures.delete(key);this.disclosures.set(key,!!detail.open)
87
+ if(this.disclosures.size>512)this.disclosures.delete(this.disclosures.keys().next().value)
88
+ }
89
+ captureDisclosures(node) {for(const detail of node.querySelectorAll('details[data-activity-key]'))this.rememberDisclosure(detail)}
90
+ restoreDisclosures(node) {for(const detail of node.querySelectorAll('details[data-activity-key]'))if(this.disclosures.has(detail.dataset.activityKey))detail.open=this.disclosures.get(detail.dataset.activityKey)}
73
91
  render(anchor, bottom=false) {
74
92
  const box=this.box, slice=this.entries.slice(this.start,Math.min(this.end,this.start+WINDOW_SIZE)), desired=[]
93
+ this.captureDisclosures(box)
75
94
  this.end=this.start+slice.length
76
95
  const rangeKey=this.start+':'+this.end
77
96
  let changed=rangeKey!==this.lastRange || this.live.innerHTML!==this.liveHtml
78
97
  this.lastRange=rangeKey
98
+ this.renderErrors=0
79
99
  for(const entry of slice) {
80
- const key=signature(entry);let cached=this.nodes.get(entry.seq)
81
- if(!cached || cached.key!==key){changed=true;const node=document.createElement('div');node.className='history-entry';node.dataset.historySeq=String(entry.seq);node.innerHTML=this.options.html(entry);cached={key,node};this.nodes.set(entry.seq,cached)}
100
+ // Hidden events render an empty string; keeping their node would leave dead gaps.
101
+ let html,key,failed=false
102
+ try{html=this.options.html(entry);key=signature(entry)}catch(error){failed=true;this.renderErrors++;key='render-error';globalThis.DshDiagnostics?.record('history.row',{phase:'failed',...globalThis.DshDiagnostics.errorFacts(error),category:'render'})}
103
+ if(!html&&!failed){if(this.nodes.delete(entry.seq))changed=true;continue}
104
+ let cached=this.nodes.get(entry.seq)
105
+ if(!cached || cached.key!==key){changed=true;const node=document.createElement('div');node.className='history-entry';node.dataset.historySeq=String(entry.seq);if(failed)node.textContent=this.options.errorLabel?.()||'This message could not be displayed. Retry loading history.';else{node.innerHTML=html;this.restoreDisclosures(node)}cached={key,node};this.nodes.set(entry.seq,cached)}
82
106
  desired.push(cached.node)
83
107
  }
84
108
  this.more.hidden=this.start===0&&!this.hasMore
85
109
  const keep=new Set(desired)
86
110
  this.suppress=true
87
- for(const child of [...box.children])if(child!==this.more && child!==this.live && child!==this.empty && !keep.has(child))child.remove()
111
+ for(const child of [...box.children])if(child!==this.more && child!==this.live && child!==this.empty && child!==this.retry && !keep.has(child))child.remove()
88
112
  if(this.more.parentNode!==box)box.prepend(this.more)
89
113
  let cursor=this.more.nextSibling
90
114
  for(const node of desired){if(node===cursor)cursor=cursor.nextSibling;else box.insertBefore(node,cursor)}
91
- if(!slice.length && !this.liveHtml){if(this.empty.parentNode!==box)box.append(this.empty)}else this.empty.remove()
92
- if(this.live.innerHTML!==this.liveHtml)this.live.innerHTML=this.liveHtml
115
+ const empty=!desired.length&&!this.liveHtml, unreadable=empty&&slice.length>0
116
+ this.empty.textContent=unreadable?(this.options.unreadableLabel?.()||this.emptyLabel):this.emptyLabel
117
+ if(empty){if(this.empty.parentNode!==box)box.append(this.empty)}else this.empty.remove()
118
+ if((unreadable||this.renderErrors)&&this.options.retry){if(this.retry.parentNode!==box)box.append(this.retry)}else this.retry.remove()
119
+ if(this.live.innerHTML!==this.liveHtml){this.live.innerHTML=this.liveHtml;this.restoreDisclosures(this.live)}
93
120
  if(this.live.parentNode!==box)box.append(this.live)
94
121
  if(bottom)box.scrollTop=box.scrollHeight
95
122
  else if(anchor){const current=this.nodes.get(anchor.seq)?.node;if(current?.parentNode===box)box.scrollTop+=current.getBoundingClientRect().top-anchor.top}
@@ -100,14 +127,15 @@
100
127
  this.options.changed?.(this)
101
128
  }
102
129
  onScroll() {
103
- const box=this.box
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
- }
130
+ const box=this.box, atBottom=this.atBottom
131
+ // Position wins over the intent flag: reaching the bottom always resumes following,
132
+ // no matter whether the scroll came from a wheel, a drag, a rail jump or momentum.
133
+ if(atBottom)this.reading=false
134
+ else if(Date.now()<this.intentUntil&&box.scrollTop<(this.lastScrollTop??box.scrollTop))this.reading=true
108
135
  this.lastScrollTop=box.scrollTop
109
136
  if(box.scrollTop<80 && Date.now()<this.intentUntil)this.older()
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)}
137
+ 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,atBottom)}
138
+ else if(atBottom&&this.end>=this.entries.length&&this.liveHtml!==(this.pendingLive||'')){this.liveHtml=this.pendingLive||'';this.render(null,true)}
111
139
  this.options.scrolled?.(this)
112
140
  this.domChanged=false
113
141
  this.options.changed?.(this)
@@ -127,7 +155,7 @@
127
155
  this.paused=false;this.box.scrollTop=this.savedScroll||0
128
156
  const pending=this.pending;this.pending=null;if(pending)this.set(pending.entries,pending.options)
129
157
  }
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()}
158
+ 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.disclosures.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()}
131
159
  }
132
160
  let cacheEpoch=0
133
161
  let database
@@ -0,0 +1,132 @@
1
+ /* Shared chat image lightbox. No dependencies, mobile and desktop. */
2
+ 'use strict';
3
+ ;(function(root){
4
+ const english=()=>root.I18N?.lang==='en'
5
+ let lightbox=null,stage=null,image=null,closeButton=null,hint=null,opener=null
6
+ let resolver=null,observer=null,mutation=null
7
+ function labels(){
8
+ if(!lightbox)return
9
+ lightbox.setAttribute('aria-label',english()?'Image preview':'图片预览')
10
+ if(closeButton)closeButton.setAttribute('aria-label',english()?'Close':'关闭')
11
+ if(hint)hint.textContent=isZoomed()?(english()?'Double-tap to fit · tap outside to close':'双击还原 · 点空白处关闭'):(english()?'Double-tap to zoom · tap outside to close':'双击放大 · 点空白处关闭')
12
+ }
13
+ function isZoomed(){return !!lightbox?.classList.contains('is-zoomed')}
14
+ function setZoom(on){
15
+ if(!lightbox)return
16
+ lightbox.classList.toggle('is-zoomed',!!on)
17
+ if(image){
18
+ if(on&&image.naturalWidth){image.style.width=image.naturalWidth*2+'px';image.style.height=image.naturalHeight*2+'px'}
19
+ else{image.style.width='';image.style.height=''}
20
+ }
21
+ if(on&&stage)root.requestAnimationFrame?.(()=>{stage.scrollLeft=(stage.scrollWidth-stage.clientWidth)/2;stage.scrollTop=(stage.scrollHeight-stage.clientHeight)/2})
22
+ labels()
23
+ }
24
+ function toggleZoom(){setZoom(!isZoomed())}
25
+ function isOpen(){return !!lightbox&&!lightbox.classList.contains('hidden')}
26
+ function open(src,alt=''){
27
+ if(!src||!elements())return
28
+ opener=root.document.activeElement||null
29
+ image.src=src
30
+ image.alt=alt||(english()?'Image':'图片')
31
+ lightbox.classList.remove('hidden')
32
+ root.document.body?.classList.add('image-preview-open')
33
+ setZoom(false)
34
+ root.requestAnimationFrame?.(()=>lightbox.focus?.({preventScroll:true}))
35
+ }
36
+ function close(){
37
+ if(!lightbox||lightbox.classList.contains('hidden'))return
38
+ setZoom(false)
39
+ lightbox.classList.add('hidden')
40
+ root.document.body?.classList.remove('image-preview-open')
41
+ image.removeAttribute?.('src')
42
+ const target=opener;opener=null
43
+ target?.focus?.({preventScroll:true})
44
+ }
45
+ // Markdown images may point at a local file. The host shell supplies an authenticated
46
+ // request for that path; load lazily and swap the placeholder for a real previewable image.
47
+ function configure(options={}){
48
+ if(typeof options.resolvePath==='function')resolver=options.resolvePath
49
+ if(!mutation&&typeof root.MutationObserver==='function'&&root.document?.body){
50
+ // History renders (paging, streaming, cache restore) replace nodes without a full render call.
51
+ mutation=new root.MutationObserver(records=>{
52
+ for(const record of records)for(const node of record.addedNodes)if(node?.nodeType===1)hydrate(node)
53
+ })
54
+ mutation.observe(root.document.body,{childList:true,subtree:true})
55
+ }
56
+ hydrate(root.document)
57
+ }
58
+ function watcher(){
59
+ if(observer)return observer
60
+ if(typeof root.IntersectionObserver!=='function')return null
61
+ observer=new root.IntersectionObserver(entries=>{
62
+ for(const entry of entries){
63
+ if(!entry.isIntersecting)continue
64
+ observer.unobserve(entry.target)
65
+ void loadPathImage(entry.target)
66
+ }
67
+ },{rootMargin:'320px'})
68
+ return observer
69
+ }
70
+ function hydrate(scope){
71
+ if(!resolver||!scope?.querySelectorAll)return
72
+ const candidates=[...(scope.matches?.('[data-chat-image][data-chat-image-path]')?[scope]:[]),...scope.querySelectorAll('[data-chat-image][data-chat-image-path]')]
73
+ for(const button of candidates){
74
+ if(button.dataset.chatImageLoading||button.dataset.chatImageLoaded)continue
75
+ button.dataset.chatImageLoading='1'
76
+ const watch=watcher()
77
+ if(watch)watch.observe(button)
78
+ else void loadPathImage(button)
79
+ }
80
+ }
81
+ async function loadPathImage(button){
82
+ const path=button.dataset.chatImagePath
83
+ if(!path||!resolver)return
84
+ try{
85
+ const source=await resolver(path)
86
+ const request=typeof source==='string'?{url:source}:source||{}
87
+ const response=await (root.fetch||fetch)(request.url,{headers:request.headers||{}})
88
+ if(!response.ok)throw new Error('HTTP '+response.status)
89
+ const blob=await response.blob()
90
+ if(!blob||!blob.size)throw new Error('empty image')
91
+ const url=root.URL?.createObjectURL?root.URL.createObjectURL(blob):''
92
+ if(!url)throw new Error('no blob url')
93
+ const node=root.document.createElement('img')
94
+ node.src=url;node.alt=button.dataset.chatImageAlt||'';node.draggable=false;node.loading='lazy'
95
+ node.addEventListener('error',()=>pathImageFailed(button))
96
+ node.addEventListener('load',()=>{button.classList.remove('is-loading');button.classList.add('is-loaded')})
97
+ button.replaceChildren(node)
98
+ button.dataset.chatImageLoaded='1'
99
+ delete button.dataset.chatImagePath
100
+ }catch(error){pathImageFailed(button)}
101
+ }
102
+ function pathImageFailed(button){
103
+ button.classList.remove('is-loading')
104
+ button.classList.add('is-error')
105
+ const status=button.querySelector?.('.chat-image-status')
106
+ if(status)status.textContent=english()?'Image unavailable':'图片无法加载'
107
+ }
108
+ function elements(){
109
+ if(lightbox)return lightbox
110
+ lightbox=root.document?.getElementById('image-lightbox')
111
+ if(!lightbox)return null
112
+ stage=lightbox.querySelector('[data-image-lightbox-stage]')
113
+ image=lightbox.querySelector('[data-image-lightbox-img]')
114
+ closeButton=lightbox.querySelector('[data-image-lightbox-close]')
115
+ hint=lightbox.querySelector('[data-image-lightbox-hint]')
116
+ closeButton?.addEventListener('click',close)
117
+ lightbox.addEventListener('click',event=>{const target=event.target;if(target===lightbox||target===stage)close()})
118
+ stage?.addEventListener('click',event=>{if(event.target===stage)close()})
119
+ image?.addEventListener('dblclick',event=>{event.preventDefault?.();toggleZoom()})
120
+ root.document.addEventListener('keydown',event=>{if(event.key==='Escape'&&isOpen()){event.preventDefault?.();close()}})
121
+ // Chat images live inside rendered history: delegate instead of rebinding per message.
122
+ root.document.addEventListener('click',event=>{
123
+ const trigger=event.target?.closest?.('[data-chat-image]')
124
+ if(!trigger)return
125
+ const img=trigger.querySelector?.('img')
126
+ if(img?.src)open(img.src,img.alt||'')
127
+ })
128
+ return lightbox
129
+ }
130
+ root.DshImagePreview={open,close,isOpen,zoom:toggleZoom,mount:elements,configure,hydrate}
131
+ root.document?.addEventListener('DOMContentLoaded',()=>{elements();hydrate(root.document)})
132
+ })(typeof window==='undefined'?globalThis:window)