dsh-remote-plugin 0.8.1 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apk/dsh-remote.apk +0 -0
- package/cordis.patch.yml +2 -1
- package/gateway.cjs +259 -12
- package/index.mjs +2 -2
- package/package.json +1 -1
- package/public/admin.html +8 -0
- package/public/admin.js +60 -0
- package/public/announcements.json +192 -0
- package/public/app.js +129 -23
- package/public/build.json +2 -2
- package/public/desktop/desktop.html +4 -4
- package/public/desktop/desktop.js +17 -9
- package/public/diagnostics.js +115 -21
- package/public/history.js +5 -4
- package/public/index.html +17 -13
- package/public/lan-discovery.js +94 -0
- package/public/styles.css +3 -0
- package/public/update.json +8 -8
- package/public/version.json +1 -1
- package/skills/dsh-remote-doctor/references/wiki/notifications.md +4 -0
|
@@ -8,7 +8,7 @@ I18N.init(window.DESKTOP_STR)
|
|
|
8
8
|
const $ = (id) => document.getElementById(id)
|
|
9
9
|
const LS = {
|
|
10
10
|
get(k, d) { try { return localStorage.getItem(k) ?? d } catch { return d } },
|
|
11
|
-
set(k, v) { try { localStorage.setItem(k, v) } catch {} },
|
|
11
|
+
set(k, v) { try { localStorage.setItem(k, v); return true } catch(error) { try { globalThis.DshDiagnostics?.storageFailure(k,error) } catch {} return false } },
|
|
12
12
|
del(k) { try { localStorage.removeItem(k) } catch {} }
|
|
13
13
|
}
|
|
14
14
|
const CLIENT_ID = (() => {
|
|
@@ -651,14 +651,16 @@ async function checkNotesOnStart() {
|
|
|
651
651
|
} catch {}
|
|
652
652
|
}
|
|
653
653
|
async function loadCrashPreview() {
|
|
654
|
+
const generation=loadCrashPreview.generation=(loadCrashPreview.generation||0)+1
|
|
654
655
|
const connection=captureConnection(),preview=$('fb-crash-preview')
|
|
655
656
|
preview.textContent=t('ds.feedbackCrashLoading')
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
657
|
+
const selected=$('fb-include-diagnostics').checked,crashes=$('fb-include-crashes').checked
|
|
658
|
+
if(!selected&&!crashes){preview.textContent=I18N.lang==='en'?'Select a log option above to preview the attachment.':'勾选上方日志选项后,可在这里预览拟上传的附件。';return}
|
|
659
|
+
const read=async route=>{try{const response=await fetch(apiUrl(route),{headers:{authorization:'Bearer '+connection.token},signal:AbortSignal.timeout(5000),cache:'no-store'});if(!response.ok)throw Error();return await response.json()}catch{return {unavailable:true}}}
|
|
660
|
+
const evidence={}
|
|
661
|
+
if(selected){evidence.client=globalThis.DshDiagnostics?.report();evidence.gateway=await read('/diagnostics')}
|
|
662
|
+
if(crashes){const data=await read('/crash-logs');evidence.crashes=data.upload||data}
|
|
663
|
+
if(connection.valid()&&generation===loadCrashPreview.generation)preview.textContent=JSON.stringify(evidence,null,2)
|
|
662
664
|
}
|
|
663
665
|
async function submitFeedback() {
|
|
664
666
|
const type = document.querySelector('#fb-chips .ds-fb-chip.current')?.dataset.fbType || 'bug'
|
|
@@ -666,6 +668,7 @@ async function submitFeedback() {
|
|
|
666
668
|
const contact = $('fb-contact').value.trim()
|
|
667
669
|
const includeDiagnostics = $('fb-include-diagnostics').checked
|
|
668
670
|
const includeCrashLogs = $('fb-include-crashes').checked
|
|
671
|
+
const clientDiagnostics=includeDiagnostics?globalThis.DshDiagnostics?.report():null
|
|
669
672
|
if (!message) { toast(t('ds.feedbackEmpty'), 'err'); return }
|
|
670
673
|
if (message.length > 2000) { toast(t('ds.feedbackTooLong'), 'err'); return }
|
|
671
674
|
const btn = $('fb-submit')
|
|
@@ -675,12 +678,15 @@ async function submitFeedback() {
|
|
|
675
678
|
const res = await fetch(apiUrl('/feedback'), {
|
|
676
679
|
method: 'POST',
|
|
677
680
|
headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token },
|
|
678
|
-
body: JSON.stringify({ type, message, contact, appVersion: '', includeDiagnostics, includeCrashLogs })
|
|
681
|
+
body: JSON.stringify({ type, message, contact, appVersion: clientDiagnostics?.client.version||'', includeDiagnostics, includeCrashLogs,...(clientDiagnostics?{clientDiagnostics}:{}) })
|
|
679
682
|
})
|
|
680
683
|
diagnostic?.end({phase:res.ok?'complete':'failed',httpStatus:res.status})
|
|
681
684
|
let json = {}
|
|
682
685
|
try { json = await res.json() } catch {}
|
|
683
|
-
if (res.ok && json.ok) {
|
|
686
|
+
if (res.ok && json.ok) { closeFeedbackModal()
|
|
687
|
+
const saved=json.diagnostics?.saved===true&&json.diagnostics.reportId===clientDiagnostics?.reportId
|
|
688
|
+
toast(clientDiagnostics&&!saved?(I18N.lang==='en'?'Feedback received; complete diagnostic report not confirmed. Copy or export the local log.':'反馈已收到,但完整诊断日志未获保存确认,请复制或导出本地日志补充。'):t('ds.feedbackSubmitted'),clientDiagnostics&&!saved?'err':'ok')
|
|
689
|
+
}
|
|
684
690
|
else if (res.status === 429) { toast(t('ds.feedbackRateLimited'), 'err') }
|
|
685
691
|
else { toast(t('ds.feedbackSubmitFailed', { msg: json.error || res.status }), 'err') }
|
|
686
692
|
} catch(error) {
|
|
@@ -4299,6 +4305,8 @@ function bindUi() {
|
|
|
4299
4305
|
$('btn-doctor').addEventListener('click', openDoctor)
|
|
4300
4306
|
$('fb-cancel').addEventListener('click', closeFeedbackModal)
|
|
4301
4307
|
$('fb-submit').addEventListener('click', submitFeedback)
|
|
4308
|
+
$('fb-include-diagnostics').addEventListener('change',()=>{void loadCrashPreview()})
|
|
4309
|
+
$('fb-include-crashes').addEventListener('change',()=>{void loadCrashPreview()})
|
|
4302
4310
|
document.querySelectorAll('#fb-chips .ds-fb-chip').forEach(btn =>
|
|
4303
4311
|
btn.addEventListener('click', () => {
|
|
4304
4312
|
document.querySelectorAll('#fb-chips .ds-fb-chip').forEach(b => b.classList.toggle('current', b === btn))
|
package/public/diagnostics.js
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
|
-
/*
|
|
1
|
+
/* Bounded support evidence. No message bodies, credentials or dependencies. */
|
|
2
2
|
'use strict'
|
|
3
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'])
|
|
4
|
+
const MAX_EVENTS=160,MAX_CRITICAL=40,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','announcement.storage','announcement.fetch','announcement.show','announcement.close','announcement.vote','storage.write','diagnostics.persist'])
|
|
6
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
7
|
enums.serviceState=['starting','running','stopped','disabled','start-failed','system-timeout','auth-expired']
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
enums.storageKey=['seen','history','votes']
|
|
9
|
+
enums.storageBackend=['session','memory']
|
|
10
|
+
enums.storageBackend.push('local','indexeddb')
|
|
11
|
+
enums.storageKey.push('settings','session-list','diagnostics','approvals','receipts')
|
|
12
|
+
enums.phase.push('received','shown','dismissed','acknowledged','skipped')
|
|
13
|
+
enums.category.push('storage','validation')
|
|
14
|
+
enums.errorName.push('QuotaExceededError','SecurityError','InvalidStateError','DataError','UnknownError')
|
|
15
|
+
enums.reason=['already-open','already-read','version-warning','empty','http','network','invalid-json','too-large','unavailable']
|
|
16
|
+
const numbers=['durationMs','httpStatus','closeCode','attempt','delayMs','count','rawCount','renderedCount','renderErrors','lastSuccessAt','intervalMin','apiLevel','storageChars','storageKeys','legacyCacheChars','legacyCacheKeys','historyCacheChars','sessionCacheChars','announcementChars','diagnosticChars','droppedEvents']
|
|
17
|
+
const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled','persisted','indexedDbAvailable','storageAvailable']
|
|
10
18
|
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
19
|
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
20
|
const hex=(v,n)=>typeof v==='string'&&new RegExp('^[a-f0-9]{'+n+'}$').test(v)?v:undefined
|
|
@@ -17,52 +25,134 @@ function createDiagnosticSchema() {
|
|
|
17
25
|
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
26
|
for(const key of booleans)if(typeof input[key]==='boolean')out[key]=input[key]
|
|
19
27
|
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]
|
|
28
|
+
for(const key of ['sessionRef','serverRef','announcementRef'])if(hex(input[key],16))out[key]=input[key]
|
|
21
29
|
if(hex(input.traceId,24))out.traceId=input.traceId
|
|
22
30
|
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
31
|
return out
|
|
24
32
|
}
|
|
33
|
+
const critical=row=>row.kind==='client.error'||row.phase==='failed'
|
|
34
|
+
function retain(events) {
|
|
35
|
+
const errors=events.filter(critical).slice(-MAX_CRITICAL),keep=new Set([...events.slice(-(MAX_EVENTS-errors.length)),...errors])
|
|
36
|
+
return events.filter(row=>keep.has(row))
|
|
37
|
+
}
|
|
38
|
+
function shrink(events,budget) {
|
|
39
|
+
while(events.length&&JSON.stringify(events).length>budget){const index=events.findIndex(row=>!critical(row));events.splice(index<0?0:index,1)}
|
|
40
|
+
return events
|
|
41
|
+
}
|
|
25
42
|
function sanitizeReport(input) {
|
|
26
43
|
if(!input||input.schema!==1||!Array.isArray(input.events))return null
|
|
27
44
|
const report={schema:1,reportId:hex(input.reportId,24)||'000000000000000000000000',capturedAt:typeof input.capturedAt==='number'&&Number.isFinite(input.capturedAt)?input.capturedAt:0,
|
|
28
45
|
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
46
|
snapshot:facts(input.snapshot),events:[]}
|
|
30
|
-
for(const item of input.events
|
|
31
|
-
|
|
47
|
+
for(const item of input.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)})
|
|
48
|
+
report.events=retain(report.events)
|
|
49
|
+
if(input.persistence&&typeof input.persistence==='object'){
|
|
50
|
+
report.persistence={}
|
|
51
|
+
for(const key of ['local','session','indexeddb'])if(['unknown','saved','failed','unavailable','pending'].includes(input.persistence[key]))report.persistence[key]=input.persistence[key]
|
|
52
|
+
}
|
|
53
|
+
while(JSON.stringify(report).length>MAX_BYTES&&report.events.length){const index=report.events.findIndex(row=>!critical(row));report.events.splice(index<0?0:index,1)}
|
|
32
54
|
return report
|
|
33
55
|
}
|
|
34
|
-
return {MAX_EVENTS,MAX_BYTES,kinds,facts,sanitizeReport
|
|
56
|
+
return {MAX_EVENTS,MAX_CRITICAL,MAX_BYTES,kinds,facts,sanitizeReport,retain,shrink,
|
|
57
|
+
definition:{MAX_EVENTS,MAX_CRITICAL,MAX_BYTES,kinds:[...kinds],enums,numbers,booleans,methods:[...methods]}}
|
|
35
58
|
}
|
|
36
59
|
;(function(root){
|
|
37
60
|
const schema=createDiagnosticSchema()
|
|
38
61
|
function createDiagnostics(env) {
|
|
39
62
|
const KEY='dshRemoteDiagnosticsV1',SALT_KEY=KEY+'Salt',MAX_AGE=86400000
|
|
40
|
-
let rows=[],timer,config={},metadata={},sequence=0,sheet,exportTimer
|
|
63
|
+
let rows=[],timer,config={},metadata={},sequence=0,sheet,exportTimer,droppedEvents=0,epoch=0
|
|
64
|
+
let database,backupJob,pendingBackup,storageAt=0,storageInventory={}
|
|
65
|
+
const persistence={local:'unknown',session:'unknown',indexeddb:'unknown'}
|
|
41
66
|
const random=()=>{const bytes=new Uint8Array(12);env.crypto?.getRandomValues?.(bytes);return [...bytes].map(n=>n.toString(16).padStart(2,'0')).join('')}
|
|
42
67
|
let salt=random(),run=random()
|
|
43
|
-
try{salt=env.localStorage.getItem(SALT_KEY)||salt;env.localStorage.setItem(SALT_KEY,salt)
|
|
68
|
+
try{salt=env.localStorage.getItem(SALT_KEY)||salt;env.localStorage.setItem(SALT_KEY,salt)}catch{}
|
|
69
|
+
for(const storage of [env.localStorage,env.sessionStorage])try{const saved=schema.sanitizeReport(JSON.parse(storage.getItem(KEY)||'null'));if(saved)rows.push(...saved.events)}catch{}
|
|
70
|
+
rows=[...new Map(rows.map(row=>[JSON.stringify(row),row])).values()].sort((a,b)=>a.at-b.at)
|
|
44
71
|
const now=()=>Date.now()
|
|
45
72
|
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)
|
|
47
|
-
function
|
|
48
|
-
|
|
49
|
-
|
|
73
|
+
const trim=()=>{const before=rows.length;rows=schema.shrink(schema.retain(rows.filter(row=>row.at>now()-MAX_AGE&&row.at<=now()+60000)),schema.MAX_BYTES-3000);droppedEvents+=before-rows.length}
|
|
74
|
+
function storageFacts(force=false){
|
|
75
|
+
if(!force&&storageAt&&now()-storageAt<30000)return storageInventory
|
|
76
|
+
const value={storageChars:0,storageKeys:0,legacyCacheChars:0,legacyCacheKeys:0,historyCacheChars:0,sessionCacheChars:0,announcementChars:0,diagnosticChars:0,indexedDbAvailable:!!env.indexedDB,storageAvailable:false}
|
|
77
|
+
try{const storage=env.localStorage;if(typeof storage.length!=='number')throw Error('storage unavailable');for(let i=0;i<storage.length;i++){
|
|
78
|
+
const key=storage.key(i),size=key.length+(storage.getItem(key)||'').length;value.storageKeys++;value.storageChars+=size
|
|
79
|
+
if(/^historyCache/.test(key)){value.historyCacheChars+=size;if(!key.includes(':session:')&&!key.endsWith(':cache-index')){value.legacyCacheChars+=size;value.legacyCacheKeys++}}
|
|
80
|
+
else if(/^sessionsCache/.test(key))value.sessionCacheChars+=size
|
|
81
|
+
else if(/^(?:seenAnnouncements|announcementHistory|announcementVotes)V1$/.test(key))value.announcementChars+=size
|
|
82
|
+
else if(key===KEY)value.diagnosticChars+=size
|
|
83
|
+
}value.storageAvailable=true}catch{}
|
|
84
|
+
storageAt=now();storageInventory=value;return value
|
|
85
|
+
}
|
|
86
|
+
function snapshot(force=false){let value={};try{value=config.snapshot?.()||{}}catch{};return schema.facts({...value,...storageFacts(force),droppedEvents,sessionRef:pseudonym(value.sessionId),serverRef:pseudonym(value.server||env.location?.origin),online:env.navigator?.onLine!==false})}
|
|
87
|
+
function makeReport(force=false){trim();return schema.sanitizeReport({schema:1,reportId:random(),capturedAt:now(),client:{...metadata,surface:config.surface||'mobile'},snapshot:snapshot(force),persistence,events:rows})}
|
|
88
|
+
const report=()=>makeReport(true)
|
|
89
|
+
function openDatabase(){
|
|
90
|
+
if(database)return database
|
|
91
|
+
if(!env.indexedDB)return Promise.resolve(null)
|
|
92
|
+
database=new Promise(resolve=>{
|
|
93
|
+
let settled=false,request
|
|
94
|
+
const done=value=>{if(settled){value?.close();return}settled=true;env.clearTimeout?.(deadline);resolve(value)}
|
|
95
|
+
const deadline=env.setTimeout?.(()=>done(null),1500)
|
|
96
|
+
try{request=env.indexedDB.open('dshRemoteDiagnosticsV1',1);request.onupgradeneeded=()=>request.result.createObjectStore('reports')
|
|
97
|
+
request.onsuccess=()=>{request.result.onversionchange=()=>{request.result.close();database=null};done(request.result)}
|
|
98
|
+
request.onerror=request.onblocked=()=>done(null)
|
|
99
|
+
}catch{done(null)}
|
|
100
|
+
})
|
|
101
|
+
return database
|
|
102
|
+
}
|
|
103
|
+
function transaction(db,mode,value){return new Promise(resolve=>{
|
|
104
|
+
let tx,result,settled=false
|
|
105
|
+
const done=value=>{if(settled)return;settled=true;env.clearTimeout?.(deadline);resolve(value)}
|
|
106
|
+
const deadline=env.setTimeout?.(()=>{done({ok:false,error:{name:'TimeoutError'}});try{tx?.abort()}catch{}},2000)
|
|
107
|
+
try{tx=db.transaction('reports',mode);const store=tx.objectStore('reports'),request=mode==='readonly'?store.get('latest'):store.put(value,'latest')
|
|
108
|
+
request.onsuccess=()=>{result=request.result}
|
|
109
|
+
tx.oncomplete=()=>done({ok:true,value:result});tx.onerror=tx.onabort=()=>done({ok:false,error:tx.error||{name:'UnknownError'}})
|
|
110
|
+
}catch(error){done({ok:false,error})}
|
|
111
|
+
})}
|
|
112
|
+
function persistFailure(backend,error){rows.push({at:now(),kind:'diagnostics.persist',phase:'failed',storageBackend:backend,...errorFacts(error)});trim()}
|
|
113
|
+
const restoredEpoch=epoch
|
|
114
|
+
const ready=openDatabase().then(async db=>{
|
|
115
|
+
if(!db){persistence.indexeddb='unavailable';return}
|
|
116
|
+
const saved=await transaction(db,'readonly')
|
|
117
|
+
if(saved.ok&&restoredEpoch===epoch){const previous=schema.sanitizeReport(saved.value),unique=new Map();for(const row of [...(previous?.events||[]),...rows])unique.set(JSON.stringify(row),row);rows=[...unique.values()].sort((a,b)=>a.at-b.at);trim()}
|
|
118
|
+
}).catch(()=>{persistence.indexeddb='failed'})
|
|
119
|
+
function backup(value){
|
|
120
|
+
pendingBackup=value
|
|
121
|
+
if(!backupJob)backupJob=(async()=>{
|
|
122
|
+
await ready;const db=await openDatabase()
|
|
123
|
+
if(!db){pendingBackup=null;persistence.indexeddb='unavailable';return}
|
|
124
|
+
while(pendingBackup){const value=makeReport();pendingBackup=null;const result=await transaction(db,'readwrite',value),previous=persistence.indexeddb;persistence.indexeddb=result.ok?'saved':'failed'
|
|
125
|
+
if(!result.ok&&previous!=='failed'){persistFailure('indexeddb',result.error);flush(false)}
|
|
126
|
+
}
|
|
127
|
+
})().catch(()=>{persistence.indexeddb='failed'}).finally(()=>{backupJob=null})
|
|
128
|
+
return backupJob
|
|
129
|
+
}
|
|
130
|
+
function flush(withBackup=true){
|
|
131
|
+
if(timer)env.clearTimeout?.(timer);timer=null
|
|
132
|
+
const previous=persistence.local
|
|
133
|
+
try{persistence.local='saved';const value=JSON.stringify(makeReport());env.localStorage.setItem(KEY,value);if(env.localStorage.getItem(KEY)!==value)throw Error('storage write unconfirmed');persistence.session='unknown';try{env.sessionStorage?.removeItem(KEY)}catch{}}
|
|
134
|
+
catch(error){persistence.local='failed';if(previous!=='failed')persistFailure('local',error)
|
|
135
|
+
try{persistence.session='saved';env.sessionStorage.setItem(KEY,JSON.stringify(makeReport()))}catch{persistence.session=env.sessionStorage?'failed':'unavailable'}
|
|
136
|
+
}
|
|
137
|
+
return withBackup?backup(makeReport()):Promise.resolve()
|
|
138
|
+
}
|
|
50
139
|
function record(kind,fields={}) {
|
|
51
140
|
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()
|
|
141
|
+
const row={at:now(),kind,...schema.facts({...fields,sessionRef:fields.sessionRef||pseudonym(fields.sessionId),serverRef:fields.serverRef||pseudonym(fields.server||env.location?.origin),announcementRef:fields.announcementRef||pseudonym(fields.announcementId)})};rows.push(row);trim()
|
|
53
142
|
if(fields.phase==='failed'||kind==='client.error'||fields.phase==='start'&&['session.open','session.back','history.load','history.render','history.cache'].includes(kind))flush()
|
|
54
143
|
else if(!timer)timer=env.setTimeout?.(flush,500)
|
|
55
144
|
return row
|
|
56
145
|
}
|
|
57
146
|
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=[]
|
|
147
|
+
const message=typeof error==='string'?error:String(error?.message||''),category=/quota|storage|indexeddb/i.test(message+' '+error?.name)?'storage':/auth|ticket|401|403/i.test(message)?'authentication':/timeout|abort/i.test(message+' '+error?.name)?'timeout':/network|fetch|socket/i.test(message)?'network':/invalid.*payload|validation|schema/i.test(message)?'validation':error?.name==='SyntaxError'?'syntax':'unknown',frames=[]
|
|
59
148
|
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
149
|
return schema.facts({category,errorName:error?.name,frames,...(/^HTTP \d{3}$/.test(message)?{httpStatus:Number(message.slice(5))}:{})})
|
|
61
150
|
}
|
|
62
151
|
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
152
|
function nativeSnapshot(){try{const value=JSON.parse(env.NativeBackground?.getBackgroundConfig?.()||'{}');return schema.facts({...value,httpStatus:value.lastHttpStatus})}catch{return {}}}
|
|
64
153
|
function configure(value){config=value;record('client.lifecycle',{status:env.document?.visibilityState==='hidden'?'hidden':'visible',...nativeSnapshot()});mount()}
|
|
65
|
-
function clear(){rows=[];flush();refreshPreview()}
|
|
154
|
+
function clear(){epoch++;rows=[];droppedEvents=0;flush();refreshPreview()}
|
|
155
|
+
function storageFailure(key,error,backend='local'){const category=/^historyCache/.test(key)?'history':/^sessionsCache/.test(key)?'session-list':key==='seenAnnouncementsV1'?'seen':key==='announcementHistoryV1'?'history':key==='announcementVotesV1'?'votes':/^dshApprovalRecordsV1/.test(key)?'approvals':'settings';storageFacts(true);return record('storage.write',{phase:'failed',storageKey:category,storageBackend:backend,...errorFacts(error)})}
|
|
66
156
|
function text(){return JSON.stringify(report(),null,2)}
|
|
67
157
|
const label=(zh,en)=>env.I18N?.lang==='en'?en:zh
|
|
68
158
|
const $=id=>env.document?.getElementById(id)
|
|
@@ -84,7 +174,7 @@ function createDiagnosticSchema() {
|
|
|
84
174
|
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
175
|
sheet=env.document.createElement('dialog');sheet.className='client-log-dialog';sheet.setAttribute('aria-labelledby','client-log-title')
|
|
86
176
|
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:['
|
|
177
|
+
const labels={entry:['查看本地操作日志','View local operation logs'],title:['本地操作日志','Local operation logs'],close:['关闭','Close'],privacy:['操作日志默认保存在此设备。提交反馈时勾选诊断选项可附带脱敏日志,也可复制或导出。','Logs stay on this device by default. Select diagnostics when submitting feedback to attach a sanitized report, or copy/export it.'],details:['查看详细记录','View detailed records'],refresh:['刷新预览','Refresh preview'],copy:['复制日志','Copy report'],export:['导出日志','Export report'],clear:['清除日志','Clear report']}
|
|
88
178
|
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
179
|
translate();if(env.MutationObserver)new env.MutationObserver(translate).observe(env.document.documentElement,{attributes:true,attributeFilter:['lang']})
|
|
90
180
|
details.addEventListener('toggle',()=>{if(details.open)refreshPreview()})
|
|
@@ -93,13 +183,17 @@ function createDiagnosticSchema() {
|
|
|
93
183
|
$('fb-log-export')?.addEventListener('click',download)
|
|
94
184
|
$('fb-log-clear')?.addEventListener('click',clear)
|
|
95
185
|
}
|
|
96
|
-
env.addEventListener?.('error',event=>
|
|
186
|
+
env.addEventListener?.('error',event=>{
|
|
187
|
+
const facts=errorFacts(event.error||event.message),file=String(event.filename||'').split(/[\\/]/).at(-1).split('?')[0]
|
|
188
|
+
if(!facts.frames?.length&&['app.js','desktop.js','history.js','activity.js','turn-results.js','network.js','operations.js','diagnostics.js'].includes(file)&&Number.isSafeInteger(event.lineno)&&event.lineno>0&&Number.isSafeInteger(event.colno)&&event.colno>0)facts.frames=[{file,line:event.lineno,column:event.colno}]
|
|
189
|
+
record('client.error',{...facts,phase:'failed'})
|
|
190
|
+
})
|
|
97
191
|
env.addEventListener?.('unhandledrejection',event=>record('client.error',{...errorFacts(event.reason),phase:'failed'}))
|
|
98
192
|
for(const status of ['online','offline'])env.addEventListener?.(status,()=>record('client.lifecycle',{status,online:status==='online'}))
|
|
99
193
|
env.document?.addEventListener('visibilitychange',()=>{record('client.lifecycle',{status:env.document.visibilityState==='visible'?'visible':'hidden',...nativeSnapshot()});flush()})
|
|
100
194
|
env.addEventListener?.('pagehide',flush)
|
|
101
195
|
function build(value){metadata={version:value?.version,buildId:value?.buildId}}
|
|
102
|
-
return {record,start,errorFacts,report,text,flush,clear,configure,show,download,build,nativeSnapshot}
|
|
196
|
+
return {record,start,errorFacts,report,text,flush,clear,configure,show,download,build,nativeSnapshot,storageFailure,storageFacts,ready}
|
|
103
197
|
}
|
|
104
198
|
if(typeof module!=='undefined'&&module.exports)module.exports={createDiagnostics,createDiagnosticSchema}
|
|
105
199
|
else {
|
package/public/history.js
CHANGED
|
@@ -185,7 +185,7 @@
|
|
|
185
185
|
if(db){const value=await new Promise(resolve=>{
|
|
186
186
|
let tx,settled=false
|
|
187
187
|
const done=value=>{if(settled)return;settled=true;clearTimeout(timer);resolve(value)}
|
|
188
|
-
|
|
188
|
+
const timer=setTimeout(()=>{globalThis.DshDiagnostics?.storageFailure(scope,{name:'TimeoutError'},'indexeddb');done(null);try{tx?.abort()}catch{}},1500)
|
|
189
189
|
try{tx=db.transaction('history');const request=tx.objectStore('history').get(key);request.onsuccess=()=>done(request.result);request.onerror=tx.onabort=tx.onerror=()=>done(null)}catch{done(null)}
|
|
190
190
|
});if(value)return value}
|
|
191
191
|
try{const value=JSON.parse(localStorage.getItem(key)||'null');if(value)return value}catch{}
|
|
@@ -202,12 +202,13 @@
|
|
|
202
202
|
const tx=db.transaction('history','readwrite'),store=tx.objectStore('history');store.put(data)
|
|
203
203
|
let count=0;const request=store.index('scopeTime').openKeyCursor(IDBKeyRange.bound([scope,0],[scope,Number.MAX_SAFE_INTEGER]),'prev')
|
|
204
204
|
request.onsuccess=()=>{const cursor=request.result;if(!cursor)return;if(++count>10)store.delete(cursor.primaryKey);cursor.continue()}
|
|
205
|
-
tx.oncomplete=()=>resolve(true);tx.onabort=tx.onerror=()=>resolve(false)
|
|
206
|
-
});if(saved)return true}catch{}
|
|
205
|
+
tx.oncomplete=()=>resolve(true);tx.onabort=tx.onerror=()=>{globalThis.DshDiagnostics?.storageFailure(scope,tx.error||{name:'UnknownError'},'indexeddb');resolve(false)}
|
|
206
|
+
});if(saved)return true}catch(error){globalThis.DshDiagnostics?.storageFailure(scope,error,'indexeddb')}
|
|
207
207
|
if(epoch!==cacheEpoch)return false
|
|
208
208
|
try{
|
|
209
209
|
const indexKey=scope+':cache-index',index=JSON.parse(localStorage.getItem(indexKey)||'[]').filter(item=>item!==key),serialized=JSON.stringify(data)
|
|
210
|
-
|
|
210
|
+
let diagnosed=false
|
|
211
|
+
while(true){try{localStorage.setItem(key,serialized);break}catch(error){if(!diagnosed){diagnosed=true;globalThis.DshDiagnostics?.storageFailure(scope,error)}if(!index.length)throw error;localStorage.removeItem(index.pop())}}
|
|
211
212
|
index.unshift(key)
|
|
212
213
|
for(const removed of index.splice(10))localStorage.removeItem(removed)
|
|
213
214
|
localStorage.setItem(indexKey,JSON.stringify(index));return kept.length>0
|
package/public/index.html
CHANGED
|
@@ -434,6 +434,7 @@
|
|
|
434
434
|
</div>
|
|
435
435
|
<div id="server-list" class="server-list"></div>
|
|
436
436
|
<div class="server-add">
|
|
437
|
+
<button id="btn-lan-discover" class="mini-btn hidden" type="button" data-i18n="settings.lanDiscover">搜索电脑</button>
|
|
437
438
|
<input id="server-input" type="url" placeholder="http://IP:8787">
|
|
438
439
|
<button id="btn-server-add" class="mini-btn" data-i18n="settings.add">添加</button>
|
|
439
440
|
</div>
|
|
@@ -464,11 +465,12 @@
|
|
|
464
465
|
<label class="switch"><input type="checkbox" id="opt-peak-remind" aria-label="峰谷计费提醒 · dsh-cost-meter"><span class="slider"></span></label>
|
|
465
466
|
</div>
|
|
466
467
|
<div class="setting-row">
|
|
467
|
-
<div><div class="setting-name" data-i18n="settings.testNotifyTitle">测试通知</div><div class="setting-desc" data-i18n="settings.testNotifyDesc"
|
|
468
|
+
<div><div class="setting-name" data-i18n="settings.testNotifyTitle">测试通知</div><div class="setting-desc" data-i18n="settings.testNotifyDesc">Android 使用所选类型的实际通知渠道测试,不执行真实任务</div></div>
|
|
469
|
+
<select id="test-notify-kind" class="setting-select" aria-label="通知测试类型"><option value="approval" data-i18n="settings.testApproval">审批提醒</option><option value="turn" data-i18n="settings.testTurn">本轮结束</option><option value="error" data-i18n="settings.testError">执行失败</option></select>
|
|
468
470
|
<button id="btn-test-notify" class="mini-btn" data-i18n="settings.testNotify">发送测试通知</button>
|
|
469
471
|
</div>
|
|
470
472
|
<div class="setting-row">
|
|
471
|
-
<div><div class="setting-name" data-i18n="settings.bgTitle">后台轮询</div><div class="setting-desc" data-i18n="settings.bgDesc"
|
|
473
|
+
<div><div class="setting-name" data-i18n="settings.bgTitle">后台轮询</div><div class="setting-desc" data-i18n="settings.bgDesc">退后台后由前台服务接收事件;系统省电与服务时限可能延迟提醒</div><div id="bg-auth-status" class="setting-desc hidden" data-i18n="settings.bgAuthFailed">登录失效:连续 3 次 401,后台轮询已停止</div></div>
|
|
472
474
|
<label class="switch"><input type="checkbox" id="opt-bg-poll"><span class="slider"></span></label>
|
|
473
475
|
</div>
|
|
474
476
|
<div class="setting-row">
|
|
@@ -481,7 +483,7 @@
|
|
|
481
483
|
</select>
|
|
482
484
|
</div>
|
|
483
485
|
<div class="setting-row">
|
|
484
|
-
<div><div class="setting-name" data-i18n="settings.taskDoneTitle">任务结束通知</div><div class="setting-desc" data-i18n="settings.taskDoneDesc"
|
|
486
|
+
<div><div class="setting-name" data-i18n="settings.taskDoneTitle">任务结束通知</div><div class="setting-desc" data-i18n="settings.taskDoneDesc">分别提醒本轮结束、目标完成与执行失败,点击进入对应会话</div></div>
|
|
485
487
|
<label class="switch"><input type="checkbox" id="opt-task-done"><span class="slider"></span></label>
|
|
486
488
|
</div>
|
|
487
489
|
<div class="setting-row">
|
|
@@ -670,10 +672,10 @@
|
|
|
670
672
|
</div>
|
|
671
673
|
<textarea id="fb-msg" class="fb-textarea" rows="5" maxlength="2000" data-i18n-placeholder="feedback.messagePlaceholder" placeholder="请描述遇到的问题或建议(必填,≤2000 字)"></textarea>
|
|
672
674
|
<input id="fb-contact" class="fb-input" maxlength="200" data-i18n-placeholder="feedback.contactPlaceholder" placeholder="联系方式(可选):邮箱 / 微信 / B站 ID">
|
|
673
|
-
<label class="fb-diagnostics"><input id="fb-include-diagnostics" type="checkbox"> <span data-i18n="feedback.includeDiagnostics"
|
|
675
|
+
<label class="fb-diagnostics"><input id="fb-include-diagnostics" type="checkbox"> <span data-i18n="feedback.includeDiagnostics">附带客户端与网关诊断(可选)</span><small data-i18n="feedback.diagnosticsPrivacy">上传客户端操作与错误位置、存储占用、版本和网关链路状态;不含令牌、Cookie、对话正文、答案或完整路径。可在下方预览。</small></label>
|
|
674
676
|
<label class="fb-diagnostics"><input id="fb-include-crashes" type="checkbox"> <span data-i18n="feedback.includeCrashes">附带崩溃日志摘要(可选)</span><small data-i18n="feedback.crashPrivacy">默认仅在本机记录。勾选后上传最近 3 条退出、重启和错误位置摘要,不含对话、密钥或完整路径。</small></label>
|
|
675
677
|
<section class="client-diagnostics" aria-label="操作诊断日志">
|
|
676
|
-
<p data-log-label="privacy"
|
|
678
|
+
<p data-log-label="privacy">操作日志默认保存在此设备。提交反馈时勾选诊断选项可附带脱敏日志,也可复制或导出。</p>
|
|
677
679
|
<details id="fb-client-log-details"><summary data-log-label="details">查看操作诊断日志</summary><pre id="fb-client-log-preview"></pre></details>
|
|
678
680
|
<div class="client-log-actions"><button id="fb-log-preview" type="button" data-log-label="refresh">刷新预览</button><button id="fb-log-copy" type="button" data-log-label="copy">复制日志</button><button id="fb-log-export" type="button" data-log-label="export">导出日志</button><button id="fb-log-clear" type="button" data-log-label="clear">清除日志</button></div>
|
|
679
681
|
<p id="fb-client-log-status" role="status" aria-live="polite"></p>
|
|
@@ -695,6 +697,7 @@
|
|
|
695
697
|
</div>
|
|
696
698
|
<div id="feedback-success-title" class="modal-title feedback-success-title" data-i18n="feedback.successTitle">反馈发送成功</div>
|
|
697
699
|
<div class="modal-body feedback-success-body" data-i18n="feedback.successBody">服务器已确认收到这条反馈,感谢你的帮助。</div>
|
|
700
|
+
<p id="feedback-diagnostics-status" class="hidden" role="status" aria-live="polite"></p>
|
|
698
701
|
<div class="modal-actions">
|
|
699
702
|
<button id="feedback-success-confirm" class="btn primary" data-i18n="feedback.successConfirm">知道了</button>
|
|
700
703
|
</div>
|
|
@@ -1160,7 +1163,7 @@
|
|
|
1160
1163
|
'settings.servers': '服务器地址(可多个)', 'settings.speedTest': '测速', 'settings.add': '添加',
|
|
1161
1164
|
'settings.scanTitle': '扫码连接', 'settings.scanDesc': '实时相机识别二维码,也可拍照/相册本地解码;无需谷歌服务', 'settings.scan': '扫码',
|
|
1162
1165
|
'settings.notifyTitle': '通知', 'settings.notifyDesc': '收到审批/提问时推送', 'settings.announcementHistoryTitle': '历史公告', 'settings.announcementHistoryDesc': '查看以前收到的公告', 'settings.announcementHistory': '查看记录',
|
|
1163
|
-
'settings.testNotifyTitle': '测试通知', 'settings.testNotifyDesc': '
|
|
1166
|
+
'settings.testApproval': '审批提醒', 'settings.testTurn': '本轮结束', 'settings.testError': '执行失败', 'settings.testNotifyTitle': '测试通知', 'settings.testNotifyDesc': 'Android 使用所选类型的实际通知渠道测试,不执行真实任务', 'settings.testNotify': '发送测试通知',
|
|
1164
1167
|
'settings.testNotifySent': '测试通知已排定,3 秒后到达', 'settings.testNotifyFailed': '发送测试通知失败:{msg}', 'settings.testNotifyUnavailable': '测试通知仅在 App 内可用',
|
|
1165
1168
|
'settings.peakRemindTitle': '峰谷计费提醒 · dsh-cost-meter', 'settings.peakRemindDesc': '按费用插件的峰谷窗口、节假日、提前量与提醒类型发送 Android 通知。无需保持 DSH 页面打开;请允许通知并将系统省电设为无限制。',
|
|
1166
1169
|
'peakRemind.enterPeak': '已进入高峰计费时段', 'peakRemind.enterOff': '已进入空闲计费时段',
|
|
@@ -1168,13 +1171,13 @@
|
|
|
1168
1171
|
'peakRemind.peak1418': '高峰 14:00-18:00', 'peakRemind.off1809': '空闲 18:00-次日 9:00',
|
|
1169
1172
|
'peakRemind.browserOnly': '峰谷提醒仅在 App 内有效',
|
|
1170
1173
|
'peakRemind.on': '峰谷提醒已开启', 'peakRemind.off': '峰谷提醒已关闭', 'peakRemind.failed': '峰谷提醒服务启动失败,请重试',
|
|
1171
|
-
'settings.bgTitle': '后台轮询', 'settings.bgDesc': '
|
|
1174
|
+
'settings.bgTitle': '后台轮询', 'settings.bgDesc': '退后台后由前台服务接收事件;系统省电与服务时限可能延迟提醒',
|
|
1172
1175
|
'settings.bgIntervalTitle': '轮询间隔', 'settings.bgIntervalDesc': '灭屏后系统可能拉长间隔(Doze 平台限制)',
|
|
1173
1176
|
'settings.bgInterval30s': '30 秒', 'settings.bgInterval1m': '1 分钟', 'settings.bgInterval5m': '5 分钟', 'settings.bgInterval15m': '15 分钟',
|
|
1174
1177
|
'settings.bgOn': '后台轮询已开启', 'settings.bgOff': '后台轮询已关闭',
|
|
1175
1178
|
'settings.bgNativeOnly': '后台轮询仅 Android App 内可用', 'settings.bgNeedToken': '请先设置访问令牌',
|
|
1176
1179
|
'settings.bgAuthFailed': '登录失效:连续 3 次 401,后台轮询已停止',
|
|
1177
|
-
'settings.taskDoneTitle': '任务结束通知', 'settings.taskDoneDesc': '
|
|
1180
|
+
'settings.lanDiscover': '搜索电脑', 'settings.taskDoneTitle': '任务结束通知', 'settings.taskDoneDesc': '分别提醒本轮结束、目标完成与执行失败,点击进入对应会话',
|
|
1178
1181
|
'bg.eventTitle': 'dsh-remote:{n} 条新事件', 'bg.eventText': '点击查看',
|
|
1179
1182
|
'presets.title': '预设提示词', 'presets.desc': '常用提示词,对话界面一键插入(最多 20 条)',
|
|
1180
1183
|
'presets.add': '新增', 'presets.edit': '编辑', 'presets.delete': '删除', 'presets.empty': '暂无预设',
|
|
@@ -1203,7 +1206,7 @@
|
|
|
1203
1206
|
'feedback.doctor': 'AI 排查问题', 'feedback.doctorDesc': '使用你的 DSH 和模型,只读诊断',
|
|
1204
1207
|
'feedback.biliDesc': 'UP 动态页交流', 'feedback.copyLink': '复制项目链接', 'feedback.copyDesc': '手动分享给朋友',
|
|
1205
1208
|
'feedback.copied': '项目链接已复制', 'feedback.copyFailed': '复制失败,请手动复制',
|
|
1206
|
-
'feedback.write': '写反馈', 'feedback.writeDesc': 'App 内直接提交', 'feedback.modalTitle': '写反馈', 'feedback.includeDiagnostics': '
|
|
1209
|
+
'feedback.write': '写反馈', 'feedback.writeDesc': 'App 内直接提交', 'feedback.modalTitle': '写反馈', 'feedback.includeDiagnostics': '附带客户端与网关诊断(可选)', 'feedback.diagnosticsPrivacy': '上传客户端操作与错误位置、存储占用、版本和网关链路状态;不含令牌、Cookie、对话正文、答案或完整路径。可在下方预览。', 'feedback.includeCrashes': '附带崩溃日志摘要(可选)', 'feedback.crashPrivacy': '默认仅在本机记录。勾选后上传最近 3 条退出、重启和错误位置摘要,不含对话、密钥或完整路径。', 'feedback.crashPreview': '查看拟上传的日志摘要', 'feedback.crashLoading': '读取本机日志…', 'feedback.crashUnavailable': '当前网关暂时无法读取日志,请更新网关或稍后重试。',
|
|
1207
1210
|
'feedback.typeBug': 'Bug', 'feedback.typeSuggestion': '建议', 'feedback.typeOther': '其他',
|
|
1208
1211
|
'feedback.messagePlaceholder': '请描述遇到的问题或建议(必填,≤2000 字)',
|
|
1209
1212
|
'feedback.contactPlaceholder': '联系方式(可选):邮箱 / 微信 / B站 ID',
|
|
@@ -1425,7 +1428,7 @@
|
|
|
1425
1428
|
'settings.servers': 'Servers (one or more)', 'settings.speedTest': 'Test', 'settings.add': 'Add',
|
|
1426
1429
|
'settings.scanTitle': 'Scan to pair', 'settings.scanDesc': 'Use the live camera or photo/gallery QR decoding; no Google services required', 'settings.scan': 'Scan',
|
|
1427
1430
|
'settings.notifyTitle': 'Notifications', 'settings.notifyDesc': 'Push on approvals / questions', 'settings.announcementHistoryTitle': 'Announcement history', 'settings.announcementHistoryDesc': 'Review announcements you received before', 'settings.announcementHistory': 'View history',
|
|
1428
|
-
'settings.testNotifyTitle': 'Test notification', 'settings.testNotifyDesc': '
|
|
1431
|
+
'settings.testNotifyTitle': 'Test notification', 'settings.testNotifyDesc': 'Test the selected Android notification channel without running a task', 'settings.testNotify': 'Send test notification',
|
|
1429
1432
|
'settings.testNotifySent': 'Test notification scheduled, arriving in 3s', 'settings.testNotifyFailed': 'Failed to send test notification: {msg}', 'settings.testNotifyUnavailable': 'Test notification is only available in the app',
|
|
1430
1433
|
'settings.peakRemindTitle': 'Peak/off-peak reminders · dsh-cost-meter', 'settings.peakRemindDesc': 'Android notifications follow the plugin’s windows, holidays, lead time and reminder type. The DSH page can be closed. Allow notifications and unrestricted battery use.',
|
|
1431
1434
|
'peakRemind.enterPeak': 'Peak pricing period started', 'peakRemind.enterOff': 'Off-peak pricing period started',
|
|
@@ -1433,13 +1436,13 @@
|
|
|
1433
1436
|
'peakRemind.peak1418': 'Peak 14:00-18:00', 'peakRemind.off1809': 'Off-peak 18:00-9:00 next day',
|
|
1434
1437
|
'peakRemind.browserOnly': 'Peak reminders only work in the app',
|
|
1435
1438
|
'peakRemind.on': 'Peak reminders enabled', 'peakRemind.off': 'Peak reminders disabled', 'peakRemind.failed': 'Could not start peak reminder service; try again',
|
|
1436
|
-
'settings.bgTitle': 'Background polling', 'settings.bgDesc': 'A foreground service
|
|
1439
|
+
'settings.bgTitle': 'Background polling', 'settings.bgDesc': 'A foreground service receives background events; system power and service limits may delay alerts',
|
|
1437
1440
|
'settings.bgIntervalTitle': 'Polling interval', 'settings.bgIntervalDesc': 'Screen-off may stretch the interval (Doze platform limit)',
|
|
1438
1441
|
'settings.bgInterval30s': '30 seconds', 'settings.bgInterval1m': '1 minute', 'settings.bgInterval5m': '5 minutes', 'settings.bgInterval15m': '15 minutes',
|
|
1439
1442
|
'settings.bgOn': 'Background polling enabled', 'settings.bgOff': 'Background polling disabled',
|
|
1440
1443
|
'settings.bgNativeOnly': 'Background polling is only available in the Android app', 'settings.bgNeedToken': 'Set an access token first',
|
|
1441
1444
|
'settings.bgAuthFailed': 'Login expired: 3 consecutive 401s, background polling stopped',
|
|
1442
|
-
'settings.taskDoneTitle': 'Task
|
|
1445
|
+
'settings.lanDiscover': 'Find computer', 'settings.testApproval': 'Approval', 'settings.testTurn': 'Turn finished', 'settings.testError': 'Execution failed', 'settings.taskDoneTitle': 'Task result notifications', 'settings.taskDoneDesc': 'Separate turn, goal and failure alerts; tap to open the session',
|
|
1443
1446
|
'bg.eventTitle': 'dsh-remote: {n} new events', 'bg.eventText': 'Tap to view',
|
|
1444
1447
|
'presets.title': 'Prompt presets', 'presets.desc': 'Common prompts, insert into the composer in one tap (max 20)',
|
|
1445
1448
|
'presets.add': 'Add', 'presets.edit': 'Edit', 'presets.delete': 'Delete', 'presets.empty': 'No presets yet',
|
|
@@ -1468,7 +1471,7 @@
|
|
|
1468
1471
|
'feedback.doctor': 'AI diagnosis', 'feedback.doctorDesc': 'Read-only diagnosis with your own DSH and model',
|
|
1469
1472
|
'feedback.biliDesc': 'Chat on the UP\'s Bilibili page', 'feedback.copyLink': 'Copy project link', 'feedback.copyDesc': 'Share it manually',
|
|
1470
1473
|
'feedback.copied': 'Project link copied', 'feedback.copyFailed': 'Copy failed, copy manually',
|
|
1471
|
-
'feedback.write': 'Write feedback', 'feedback.writeDesc': 'Submit from the app', 'feedback.modalTitle': 'Write feedback', 'feedback.includeDiagnostics': 'Include
|
|
1474
|
+
'feedback.write': 'Write feedback', 'feedback.writeDesc': 'Submit from the app', 'feedback.modalTitle': 'Write feedback', 'feedback.includeDiagnostics': 'Include client and gateway diagnostics (optional)', 'feedback.diagnosticsPrivacy': 'Uploads operation stages, error locations, storage sizes, versions and gateway status. No credentials, conversation bodies, answers or full paths. Preview below.', 'feedback.includeCrashes': 'Include crash summary (optional)', 'feedback.crashPrivacy': 'Recorded locally by default. Opt in to upload up to 3 recent exit, restart and error-location records. No conversations, credentials or full paths.', 'feedback.crashPreview': 'Preview the log summary to upload', 'feedback.crashLoading': 'Reading local logs…', 'feedback.crashUnavailable': 'Logs are unavailable. Update the gateway or try again later.',
|
|
1472
1475
|
'feedback.typeBug': 'Bug', 'feedback.typeSuggestion': 'Suggestion', 'feedback.typeOther': 'Other',
|
|
1473
1476
|
'feedback.messagePlaceholder': 'Describe the bug or suggestion (required, ≤2000 chars)',
|
|
1474
1477
|
'feedback.contactPlaceholder': 'Contact (optional): email / WeChat / Bilibili ID',
|
|
@@ -1530,6 +1533,7 @@
|
|
|
1530
1533
|
<script src="file-inbox.js"></script>
|
|
1531
1534
|
<link rel="stylesheet" href="session-deck.css">
|
|
1532
1535
|
<script src="session-deck.js"></script>
|
|
1536
|
+
<script src="lan-discovery.js"></script>
|
|
1533
1537
|
<script src="app.js"></script>
|
|
1534
1538
|
</body>
|
|
1535
1539
|
</html>
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/* Android system bridge; browsers keep the existing QR/manual connection paths. */
|
|
2
|
+
;(function(root) {
|
|
3
|
+
'use strict'
|
|
4
|
+
root.DshLanDiscovery = { mount(button, paired) {
|
|
5
|
+
const bridge = root.NativeLan
|
|
6
|
+
if (!button || !bridge?.search) return
|
|
7
|
+
button.classList.remove('hidden')
|
|
8
|
+
const en = () => root.I18N?.lang === 'en'
|
|
9
|
+
const text = (zh, english) => en() ? english : zh
|
|
10
|
+
let modal, timer, selected = '', hosts = [], signature = '', busy = false, open = false
|
|
11
|
+
function status(value) { modal.querySelector('[data-lan-status]').textContent = value }
|
|
12
|
+
function close() {
|
|
13
|
+
open = false; clearTimeout(timer); bridge.cancel(); modal?.remove(); modal = null
|
|
14
|
+
button.focus()
|
|
15
|
+
}
|
|
16
|
+
function search() {
|
|
17
|
+
selected = ''; signature = ''; hosts = []; busy = false
|
|
18
|
+
modal.querySelector('[data-lan-pair]').classList.add('hidden')
|
|
19
|
+
modal.querySelector('[data-lan-list]').replaceChildren()
|
|
20
|
+
status(text('正在搜索同一 Wi-Fi 下开放配对的电脑…', 'Searching for computers accepting pairing on this Wi-Fi…'))
|
|
21
|
+
bridge.search()
|
|
22
|
+
clearTimeout(timer); tick()
|
|
23
|
+
}
|
|
24
|
+
function tick() {
|
|
25
|
+
if (!open || !modal) return
|
|
26
|
+
try {
|
|
27
|
+
const state = JSON.parse(bridge.getState() || '{}')
|
|
28
|
+
busy = state.phase === 'pairing'
|
|
29
|
+
modal.querySelector('[data-lan-search]').disabled = busy
|
|
30
|
+
modal.querySelector('[data-lan-connect]').disabled = busy
|
|
31
|
+
modal.querySelector('[data-lan-code]').disabled = busy
|
|
32
|
+
const entries = Array.isArray(state.hosts) ? state.hosts.slice(0, 32) : []
|
|
33
|
+
const next = JSON.stringify(entries)
|
|
34
|
+
if (next !== signature) {
|
|
35
|
+
signature = next; hosts = entries
|
|
36
|
+
const list = modal.querySelector('[data-lan-list]'); list.replaceChildren()
|
|
37
|
+
for (const host of hosts) {
|
|
38
|
+
const entry = document.createElement('button'); entry.type = 'button'; entry.className = 'btn subtle'
|
|
39
|
+
entry.textContent = String(host.name || 'DSH Remote') + ' · ' + String(host.server || '')
|
|
40
|
+
entry.addEventListener('click', () => {
|
|
41
|
+
if (busy) return
|
|
42
|
+
selected = host.id
|
|
43
|
+
modal.querySelector('[data-lan-selected]').textContent = String(host.name || host.server)
|
|
44
|
+
modal.querySelector('[data-lan-pair]').classList.remove('hidden')
|
|
45
|
+
modal.querySelector('[data-lan-code]').focus()
|
|
46
|
+
}); list.append(entry)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (state.phase === 'paired') {
|
|
50
|
+
const result = JSON.parse(bridge.takePairResult() || '{}')
|
|
51
|
+
if (!hosts.some(host => host.server === result.server) || typeof result.token !== 'string') throw Error('PAIRING_RESPONSE_INVALID')
|
|
52
|
+
// Close before applying credentials, so no stale poll can apply them a second time.
|
|
53
|
+
close(); paired(result); return
|
|
54
|
+
}
|
|
55
|
+
if (state.phase === 'pairing') status(text('正在验证配对码并连接…', 'Verifying the pairing code…'))
|
|
56
|
+
else if (state.phase === 'done') status(hosts.length ? text('请选择电脑并输入配对码。', 'Select a computer and enter its pairing code.')
|
|
57
|
+
: text('没有找到电脑。请在电脑端开启局域网配对,确认同一 Wi-Fi;也可继续扫码或手动连接。', 'No computers found. Open LAN pairing on the computer and check Wi-Fi, or use QR/manual connection.'))
|
|
58
|
+
else if (state.phase === 'error') {
|
|
59
|
+
const errors = {
|
|
60
|
+
WIFI_REQUIRED: text('请先连接 Wi-Fi。', 'Connect to Wi-Fi first.'),
|
|
61
|
+
NETWORK_PERMISSION_REQUIRED: text('请检查系统网络访问权限。', 'Check system network permissions.'),
|
|
62
|
+
PAIRING_CODE_INVALID: text('配对码不匹配,请核对电脑端显示的配对码。', 'Pairing code does not match the computer.'),
|
|
63
|
+
PAIRING_CLOSED: text('配对已关闭或过期,请在电脑端重新开启。', 'Pairing expired or closed. Reopen it on the computer.'),
|
|
64
|
+
}
|
|
65
|
+
status(errors[state.error] || text('搜索或配对失败,请检查网络后重试;也可扫码连接。', 'Search or pairing failed. Check the network or use QR pairing.'))
|
|
66
|
+
}
|
|
67
|
+
} catch { if (modal) status(text('无法读取搜索状态,请重新搜索。', 'Unable to read discovery status. Search again.')) }
|
|
68
|
+
timer = setTimeout(tick, 300)
|
|
69
|
+
}
|
|
70
|
+
button.addEventListener('click', () => {
|
|
71
|
+
if (open) return
|
|
72
|
+
open = true
|
|
73
|
+
modal = document.createElement('div'); modal.className = 'modal'; modal.setAttribute('role', 'dialog'); modal.setAttribute('aria-modal', 'true')
|
|
74
|
+
modal.innerHTML = '<div class="modal-card lan-discovery-card"><div class="modal-title" data-lan-title></div><p data-lan-status role="status" aria-live="polite"></p><div data-lan-list class="lan-host-list"></div><div data-lan-pair class="hidden"><p data-lan-selected></p><label><span data-lan-label></span><input data-lan-code type="password" maxlength="24" autocomplete="off" spellcheck="false" placeholder="XXXX-XXXX-XXXX-XXXX-XXXX"></label><button data-lan-connect class="btn primary" type="button"></button></div><div class="modal-actions"><button data-lan-search class="btn subtle" type="button"></button><button data-lan-close class="btn subtle" type="button"></button></div></div>'
|
|
75
|
+
modal.querySelector('[data-lan-title]').textContent = text('搜索局域网电脑', 'Find a computer on Wi-Fi')
|
|
76
|
+
modal.querySelector('[data-lan-label]').textContent = text('电脑端显示的限时配对码', 'One-time code shown on the computer')
|
|
77
|
+
modal.querySelector('[data-lan-connect]').textContent = text('配对连接', 'Pair and connect')
|
|
78
|
+
modal.querySelector('[data-lan-search]').textContent = text('重新搜索', 'Search again')
|
|
79
|
+
modal.querySelector('[data-lan-close]').textContent = text('关闭', 'Close')
|
|
80
|
+
modal.querySelector('[data-lan-close]').addEventListener('click', close)
|
|
81
|
+
modal.querySelector('[data-lan-search]').addEventListener('click', search)
|
|
82
|
+
modal.querySelector('[data-lan-connect]').addEventListener('click', () => {
|
|
83
|
+
if (busy) return
|
|
84
|
+
const input = modal.querySelector('[data-lan-code]'), code = input.value
|
|
85
|
+
if (!selected || !/^[a-f0-9]{20}$/i.test(code.replace(/[\s-]/g, ''))) return status(text('请选择电脑,输入完整的 20 位配对码。', 'Select a computer and enter the full 20-character code.'))
|
|
86
|
+
if (!bridge.pair(selected, code)) return status(text('无法开始配对,请重新搜索后重试。', 'Could not start pairing. Search again.'))
|
|
87
|
+
input.value = ''; busy = true; clearTimeout(timer); tick()
|
|
88
|
+
})
|
|
89
|
+
modal.addEventListener('keydown', event => { if (event.key === 'Escape') { event.preventDefault(); close() } })
|
|
90
|
+
document.body.append(modal); modal.querySelector('[data-lan-search]').focus(); search()
|
|
91
|
+
})
|
|
92
|
+
document.addEventListener('visibilitychange', () => { if (document.hidden && open) close() })
|
|
93
|
+
} }
|
|
94
|
+
})(typeof window === 'object' ? window : globalThis)
|
package/public/styles.css
CHANGED
|
@@ -1428,3 +1428,6 @@ body.in-session #session-sub { min-height:32px; padding:4px 2px; }
|
|
|
1428
1428
|
.chat-file { display:flex; flex-wrap:wrap; align-items:center; gap:8px 12px; padding:12px; border:1px solid var(--dsr-line); border-radius:12px; margin:8px 0; }
|
|
1429
1429
|
.chat-file-name { min-width:0; flex:1; overflow-wrap:break-word; }.chat-file small { color:var(--dsr-muted); }
|
|
1430
1430
|
.chat-file button { flex-shrink:0; min-height:44px; padding:8px 12px; border:1px solid var(--dsr-accent-line); border-radius:10px; color:var(--dsr-accent-strong); background:var(--dsr-accent-soft); font:inherit; cursor:pointer; }
|
|
1431
|
+
.lan-host-list { display:flex; flex-direction:column; gap:8px; max-height:35vh; overflow:auto; }
|
|
1432
|
+
.lan-host-list button { min-height:44px; overflow-wrap:anywhere; white-space:normal; text-align:start; }
|
|
1433
|
+
.lan-discovery-card input { display:block; width:100%; min-height:44px; margin:8px 0; padding:10px; background:var(--dsr-bg); color:var(--dsr-text); border:1px solid var(--dsr-line); border-radius:8px; }
|