@hyprnos/dsh-remote-plugin 0.0.0-stage → 0.8.9
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/README.en.md +61 -0
- package/README.md +60 -2
- package/apk/dsh-remote.apk +0 -0
- package/approval-summary.mjs +115 -0
- package/client.js +197 -0
- package/cordis.patch.yml +5 -0
- package/doctor-skill.mjs +99 -0
- package/doctor-target.mjs +24 -0
- package/file-delivery.mjs +84 -0
- package/gateway-stats.cjs +501 -0
- package/gateway.cjs +8451 -0
- package/index.mjs +1788 -0
- package/insights.mjs +111 -0
- package/market.mjs +86 -0
- package/package.json +73 -4
- package/peak-reminders.mjs +50 -0
- package/plugin-center.mjs +777 -0
- package/plugin-transaction.mjs +300 -0
- package/public/activity.js +188 -0
- package/public/admin.html +820 -0
- package/public/admin.js +1167 -0
- package/public/announcement-forms.js +89 -0
- package/public/announcements.json +464 -0
- package/public/app.js +8826 -0
- package/public/approval-records.js +301 -0
- package/public/approval-summary.js +78 -0
- package/public/build.json +5 -0
- package/public/cache-upgrade.js +51 -0
- package/public/chat-copy.js +59 -0
- package/public/chat-files.js +87 -0
- package/public/desktop/desktop.css +816 -0
- package/public/desktop/desktop.html +871 -0
- package/public/desktop/desktop.js +4548 -0
- package/public/desktop/i18n.js +85 -0
- package/public/diagnostics.js +203 -0
- package/public/doctor-entry.js +94 -0
- package/public/doctor.css +205 -0
- package/public/doctor.js +769 -0
- package/public/donate.png +0 -0
- package/public/e2ee-transport.js +219 -0
- package/public/extensions.css +109 -0
- package/public/extensions.js +215 -0
- package/public/file-inbox.css +66 -0
- package/public/file-inbox.js +289 -0
- package/public/genui.css +8 -0
- package/public/genui.js +254 -0
- package/public/history.js +304 -0
- package/public/i18n.js +57 -0
- package/public/icon.svg +12 -0
- package/public/image-cache.js +141 -0
- package/public/image-preview.js +290 -0
- package/public/index.html +1568 -0
- package/public/insights.css +28 -0
- package/public/insights.js +290 -0
- package/public/jsqr.min.js +10104 -0
- package/public/lan-discovery.js +94 -0
- package/public/link-check.js +109 -0
- package/public/manifest.webmanifest +16 -0
- package/public/md.js +333 -0
- package/public/morphicons-init.js +41 -0
- package/public/motion.js +557 -0
- package/public/network.js +100 -0
- package/public/onboarding.css +36 -0
- package/public/onboarding.js +253 -0
- package/public/operations.js +141 -0
- package/public/permission-presets.js +159 -0
- package/public/plugin-center.css +120 -0
- package/public/plugin-center.js +666 -0
- package/public/plugin-icon.svg +5 -0
- package/public/plugin.html +68 -0
- package/public/plugin.js +211 -0
- package/public/qrcode.min.js +2297 -0
- package/public/relay-autopair.js +251 -0
- package/public/relay-devices.js +80 -0
- package/public/relay-settings.css +24 -0
- package/public/relay-settings.js +194 -0
- package/public/remote-state.js +27 -0
- package/public/remote-ui.css +148 -0
- package/public/remote-ui.js +243 -0
- package/public/session-deck.css +79 -0
- package/public/session-deck.js +180 -0
- package/public/session-presets.js +47 -0
- package/public/setup.css +18 -0
- package/public/setup.js +213 -0
- package/public/sha256.js +119 -0
- package/public/skills.css +81 -0
- package/public/skills.js +202 -0
- package/public/skins/blue-fish/DESIGN.md +24 -0
- package/public/skins/blue-fish/face.png +0 -0
- package/public/skins/blue-fish/icon-blush.png +0 -0
- package/public/skins/blue-fish/icon-sleep.png +0 -0
- package/public/skins/blue-fish/icon-smile.png +0 -0
- package/public/skins/blue-fish/icon-star.png +0 -0
- package/public/skins/blue-fish/icon-wink.png +0 -0
- package/public/skins/blue-fish/icon.png +0 -0
- package/public/skins/blue-fish/mascot.png +0 -0
- package/public/skins/blue-fish/pattern.png +0 -0
- package/public/skins/blue-fish/preview.html +12 -0
- package/public/skins/blue-fish/skin.css +122 -0
- package/public/skins/blue-fish/sparkles.svg +18 -0
- package/public/skins/bocchi/DESIGN.md +99 -0
- package/public/skins/bocchi/face.png +0 -0
- package/public/skins/bocchi/grain.png +0 -0
- package/public/skins/bocchi/icon-blush.png +0 -0
- package/public/skins/bocchi/icon-sleep.png +0 -0
- package/public/skins/bocchi/icon-smile.png +0 -0
- package/public/skins/bocchi/icon-star.png +0 -0
- package/public/skins/bocchi/icon-wink.png +0 -0
- package/public/skins/bocchi/icon.png +0 -0
- package/public/skins/bocchi/pattern-soft.png +0 -0
- package/public/skins/bocchi/pattern.png +0 -0
- package/public/skins/bocchi/preview.html +55 -0
- package/public/skins/bocchi/skin.css +233 -0
- package/public/skins/bocchi/stage-bg.png +0 -0
- package/public/skins/bocchi/stage-soft.png +0 -0
- package/public/skins/bocchi/stand.png +0 -0
- package/public/skins/bocchi/sticker-guitar.png +0 -0
- package/public/skins/kessoku/DESIGN.md +38 -0
- package/public/skins/kessoku/grain.png +0 -0
- package/public/skins/kessoku/skin.css +212 -0
- package/public/skins/kita/SOURCES.json +51 -0
- package/public/skins/kita/face.png +0 -0
- package/public/skins/kita/icon-live.png +0 -0
- package/public/skins/kita/icon-reddress.png +0 -0
- package/public/skins/kita/icon-seifuku.png +0 -0
- package/public/skins/kita/pattern.png +0 -0
- package/public/skins/kita/preview.html +56 -0
- package/public/skins/kita/skin.css +26 -0
- package/public/skins/kita/stand.png +0 -0
- package/public/skins/kita/sticker-live.png +0 -0
- package/public/skins/nijika/SOURCES.json +51 -0
- package/public/skins/nijika/face.png +0 -0
- package/public/skins/nijika/icon-live.png +0 -0
- package/public/skins/nijika/icon-reddress.png +0 -0
- package/public/skins/nijika/icon-seifuku.png +0 -0
- package/public/skins/nijika/pattern.png +0 -0
- package/public/skins/nijika/preview.html +56 -0
- package/public/skins/nijika/skin.css +25 -0
- package/public/skins/nijika/stand.png +0 -0
- package/public/skins/nijika/sticker-live.png +0 -0
- package/public/skins/penguin/DESIGN.md +33 -0
- package/public/skins/penguin/SOURCES.json +22 -0
- package/public/skins/penguin/aic-blueprint.svg +24 -0
- package/public/skins/penguin/endfield-triangles.svg +4 -0
- package/public/skins/penguin/face.png +0 -0
- package/public/skins/penguin/icon-blush.png +0 -0
- package/public/skins/penguin/icon-dizzy.png +0 -0
- package/public/skins/penguin/icon-laugh.png +0 -0
- package/public/skins/penguin/icon-sleep.png +0 -0
- package/public/skins/penguin/icon-smile.png +0 -0
- package/public/skins/penguin/icon-star.png +0 -0
- package/public/skins/penguin/icon-wink.png +0 -0
- package/public/skins/penguin/icon.png +0 -0
- package/public/skins/penguin/mascot.png +0 -0
- package/public/skins/penguin/pattern-night.png +0 -0
- package/public/skins/penguin/pattern.png +0 -0
- package/public/skins/penguin/preview.html +12 -0
- package/public/skins/penguin/skin.css +212 -0
- package/public/skins/ryo/SOURCES.json +51 -0
- package/public/skins/ryo/face.png +0 -0
- package/public/skins/ryo/icon-live.png +0 -0
- package/public/skins/ryo/icon-reddress.png +0 -0
- package/public/skins/ryo/icon-seifuku.png +0 -0
- package/public/skins/ryo/pattern.png +0 -0
- package/public/skins/ryo/preview.html +56 -0
- package/public/skins/ryo/skin.css +25 -0
- package/public/skins/ryo/stand.png +0 -0
- package/public/skins/ryo/sticker-live.png +0 -0
- package/public/sponsor-entry.js +21 -0
- package/public/styles.css +1526 -0
- package/public/subagents.css +61 -0
- package/public/subagents.js +275 -0
- package/public/task-board.js +109 -0
- package/public/teams.js +98 -0
- package/public/theme-picker.css +58 -0
- package/public/theme-vars.css +1044 -0
- package/public/theme.js +166 -0
- package/public/transcribe-core.js +74 -0
- package/public/turn-results.js +121 -0
- package/public/update.json +49 -0
- package/public/vendor/gsap/NOTICE.md +10 -0
- package/public/vendor/gsap/gsap.min.js +11 -0
- package/public/vendor/morphicons/LICENSE +21 -0
- package/public/vendor/morphicons/README.md +10 -0
- package/public/vendor/morphicons/controller-CXZuwJ_M.js +152 -0
- package/public/vendor/morphicons/dom.js +206 -0
- package/public/vendor/morphicons/element.js +261 -0
- package/public/vendor/morphicons/normalize-CYnN3Npw.js +540 -0
- package/public/vendor/morphicons/spring-CFHloqPP.js +623 -0
- package/public/version.json +3 -0
- package/public/voice-input.js +1151 -0
- package/public/workflow.css +365 -0
- package/public/workflow.js +419 -0
- package/session-file.mjs +39 -0
- package/skills/dsh-remote-doctor/SKILL.md +186 -0
- package/skills/dsh-remote-doctor/references/wiki/README.md +40 -0
- package/skills/dsh-remote-doctor/references/wiki/ai-guide.md +61 -0
- package/skills/dsh-remote-doctor/references/wiki/connection.md +76 -0
- package/skills/dsh-remote-doctor/references/wiki/errors.md +26 -0
- package/skills/dsh-remote-doctor/references/wiki/evidence.md +44 -0
- package/skills/dsh-remote-doctor/references/wiki/files.md +31 -0
- package/skills/dsh-remote-doctor/references/wiki/maintenance.md +30 -0
- package/skills/dsh-remote-doctor/references/wiki/notifications.md +33 -0
- package/skills/dsh-remote-doctor/references/wiki/operations.md +32 -0
- package/skills/dsh-remote-doctor/references/wiki/plugins.md +90 -0
- package/skills/dsh-remote-doctor/references/wiki/sessions.md +45 -0
- package/skills/dsh-remote-doctor/references/wiki/sources.md +27 -0
- package/skills.mjs +53 -0
- package/speech-whisper.mjs +705 -0
- package/task-board.mjs +57 -0
- package/teams.mjs +58 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/* DSH Remote 桌面端轻量 i18n · 零依赖(与 public/i18n.js 同构) */
|
|
2
|
+
'use strict'
|
|
3
|
+
;(function () {
|
|
4
|
+
const store = {
|
|
5
|
+
get(k) { try { return localStorage.getItem(k) } catch { return null } },
|
|
6
|
+
set(k, v) { try { localStorage.setItem(k, v) } catch {} }
|
|
7
|
+
}
|
|
8
|
+
function detect() {
|
|
9
|
+
const saved = store.get('dshLang')
|
|
10
|
+
if (saved === 'zh' || saved === 'en') return saved
|
|
11
|
+
return (navigator.language || 'zh').toLowerCase().startsWith('zh') ? 'zh' : 'en'
|
|
12
|
+
}
|
|
13
|
+
const BUILTIN = {
|
|
14
|
+
zh: {
|
|
15
|
+
'wb.unbound': 'DSH Remote(未绑定)', 'wb.bind': '绑定工作台', 'wb.bound': 'DSH Remote(绑定 {title})',
|
|
16
|
+
'wb.viewPath': '已绑定 workspace', 'wb.unbind': '解绑', 'wb.unbindConfirm': '确定解绑当前工作台?解绑后这些会话将回到扁平会话列表。',
|
|
17
|
+
'wb.modalTitle': '绑定工作台', 'wb.modalDesc': '选择工作台根目录,其下每个子文件夹会自动成为项目工作区。',
|
|
18
|
+
'wb.up': '上级', 'wb.home': '根目录', 'wb.selectDir': '选择此目录', 'wb.pathPlaceholder': '或手动输入绝对路径…',
|
|
19
|
+
'wb.pathEmpty': '请输入要绑定的路径', 'wb.empty': '此目录没有子文件夹', 'wb.boundOk': '工作台已绑定:{path}',
|
|
20
|
+
'wb.bindFailed': '绑定失败:{msg}', 'wb.unboundOk': '已解绑工作台', 'wb.unbindFailed': '解绑失败:{msg}',
|
|
21
|
+
'wb.boundPath': '绑定路径:{path}', 'wb.projects': '项目', 'wb.noProjects': '暂无项目(根目录下新建文件夹后会自动出现)',
|
|
22
|
+
'wb.newSession': '新会话', 'wb.noSessions': '暂无会话', 'wb.flatHidden': '工作台会话已收起({n} 个在工作台面板)',
|
|
23
|
+
'wb.apiMissing': '工作台接口不可用(需更新网关)', 'wb.loadFailed': '工作台加载失败:{msg}',
|
|
24
|
+
'wb.archivedHidden': '------隐藏已归档会话------', 'wb.archivedShown': '------显示已归档会话------'
|
|
25
|
+
},
|
|
26
|
+
en: {
|
|
27
|
+
'wb.unbound': 'DSH Remote (unbound)', 'wb.bind': 'Bind workbench', 'wb.bound': 'DSH Remote (bound {title})',
|
|
28
|
+
'wb.viewPath': 'Bound workspace', 'wb.unbind': 'Unbind', 'wb.unbindConfirm': 'Unbind the current workbench? These sessions will return to the flat list.',
|
|
29
|
+
'wb.modalTitle': 'Bind workbench', 'wb.modalDesc': 'Choose the workbench root; each subfolder becomes a project workspace automatically.',
|
|
30
|
+
'wb.up': 'Up', 'wb.home': 'Root', 'wb.selectDir': 'Select this folder', 'wb.pathPlaceholder': 'Or type an absolute path…',
|
|
31
|
+
'wb.pathEmpty': 'Enter a path to bind', 'wb.empty': 'No subfolders in this folder', 'wb.boundOk': 'Workbench bound: {path}',
|
|
32
|
+
'wb.bindFailed': 'Bind failed: {msg}', 'wb.unboundOk': 'Workbench unbound', 'wb.unbindFailed': 'Unbind failed: {msg}',
|
|
33
|
+
'wb.boundPath': 'Bound path: {path}', 'wb.projects': 'Projects', 'wb.noProjects': 'No projects yet',
|
|
34
|
+
'wb.newSession': 'New session', 'wb.noSessions': 'No sessions', 'wb.flatHidden': 'Workbench sessions folded ({n} in the workbench panel)',
|
|
35
|
+
'wb.apiMissing': 'Workbench API unavailable (update gateway)', 'wb.loadFailed': 'Workbench load failed: {msg}',
|
|
36
|
+
'wb.archivedHidden': '------ Hide archived ------', 'wb.archivedShown': '------ Show archived ------'
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function mergeDicts(strings) {
|
|
40
|
+
return {
|
|
41
|
+
zh: Object.assign({}, BUILTIN.zh, strings?.zh || {}),
|
|
42
|
+
en: Object.assign({}, BUILTIN.en, strings?.en || {})
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
let dict = null
|
|
46
|
+
let lang = detect()
|
|
47
|
+
|
|
48
|
+
function t(key, vars) {
|
|
49
|
+
const table = (dict && (dict[lang] || dict.zh)) || {}
|
|
50
|
+
let s = table[key]
|
|
51
|
+
if (s == null) s = (dict && dict.zh && dict.zh[key]) != null ? dict.zh[key] : key
|
|
52
|
+
s = String(s)
|
|
53
|
+
if (vars) {
|
|
54
|
+
const keys = new Set(Object.keys(vars))
|
|
55
|
+
s = s.replace(/\{([A-Za-z0-9_]+)\}/g, (m, k) => keys.has(k) ? String(vars[k] ?? '') : '')
|
|
56
|
+
} else {
|
|
57
|
+
s = s.replace(/\{[A-Za-z0-9_]+\}/g, '')
|
|
58
|
+
}
|
|
59
|
+
return s
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function apply(root) {
|
|
63
|
+
root = root || document
|
|
64
|
+
root.querySelectorAll('[data-i18n]').forEach(el => { el.textContent = t(el.getAttribute('data-i18n')) })
|
|
65
|
+
root.querySelectorAll('[data-i18n-title]').forEach(el => { el.title = t(el.getAttribute('data-i18n-title')) })
|
|
66
|
+
root.querySelectorAll('[data-i18n-placeholder]').forEach(el => { el.placeholder = t(el.getAttribute('data-i18n-placeholder')) })
|
|
67
|
+
root.querySelectorAll('[data-i18n-aria]').forEach(el => { el.setAttribute('aria-label', t(el.getAttribute('data-i18n-aria'))) })
|
|
68
|
+
document.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en'
|
|
69
|
+
return lang
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function setLang(l) {
|
|
73
|
+
if (l !== 'zh' && l !== 'en') return lang
|
|
74
|
+
lang = l
|
|
75
|
+
store.set('dshLang', l)
|
|
76
|
+
apply(document)
|
|
77
|
+
return lang
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
window.I18N = {
|
|
81
|
+
init(strings) { dict = mergeDicts(strings || dict || {}); return apply(document) },
|
|
82
|
+
t, setLang, apply,
|
|
83
|
+
get lang() { return lang }
|
|
84
|
+
}
|
|
85
|
+
})()
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/* Bounded support evidence. No message bodies, credentials or dependencies. */
|
|
2
|
+
'use strict'
|
|
3
|
+
function createDiagnosticSchema() {
|
|
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
|
+
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
|
+
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']
|
|
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'])
|
|
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)
|
|
20
|
+
const hex=(v,n)=>typeof v==='string'&&new RegExp('^[a-f0-9]{'+n+'}$').test(v)?v:undefined
|
|
21
|
+
const version=v=>typeof v==='string'&&/^\d+\.\d+\.\d+(?:[.-][a-zA-Z0-9.-]{1,30})?$/.test(v)?v:'unknown'
|
|
22
|
+
function facts(input={}) {
|
|
23
|
+
const out={}
|
|
24
|
+
for(const [key,values]of Object.entries(enums))if(values.includes(input[key]))out[key]=input[key]
|
|
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)
|
|
26
|
+
for(const key of booleans)if(typeof input[key]==='boolean')out[key]=input[key]
|
|
27
|
+
if(methods.has(input.method))out.method=input.method
|
|
28
|
+
for(const key of ['sessionRef','serverRef','announcementRef'])if(hex(input[key],16))out[key]=input[key]
|
|
29
|
+
if(hex(input.traceId,24))out.traceId=input.traceId
|
|
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}))
|
|
31
|
+
return out
|
|
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
|
+
}
|
|
42
|
+
function sanitizeReport(input) {
|
|
43
|
+
if(!input||input.schema!==1||!Array.isArray(input.events))return null
|
|
44
|
+
const report={schema:1,reportId:hex(input.reportId,24)||'000000000000000000000000',capturedAt:typeof input.capturedAt==='number'&&Number.isFinite(input.capturedAt)?input.capturedAt:0,
|
|
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'},
|
|
46
|
+
snapshot:facts(input.snapshot),events:[]}
|
|
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)}
|
|
54
|
+
return report
|
|
55
|
+
}
|
|
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]}}
|
|
58
|
+
}
|
|
59
|
+
;(function(root){
|
|
60
|
+
const schema=createDiagnosticSchema()
|
|
61
|
+
function createDiagnostics(env) {
|
|
62
|
+
const KEY='dshRemoteDiagnosticsV1',SALT_KEY=KEY+'Salt',MAX_AGE=86400000
|
|
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'}
|
|
66
|
+
const random=()=>{const bytes=new Uint8Array(12);env.crypto?.getRandomValues?.(bytes);return [...bytes].map(n=>n.toString(16).padStart(2,'0')).join('')}
|
|
67
|
+
let salt=random(),run=random()
|
|
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)
|
|
71
|
+
const now=()=>Date.now()
|
|
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}}
|
|
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
|
+
}
|
|
139
|
+
function record(kind,fields={}) {
|
|
140
|
+
if(!schema.kinds.has(kind))return
|
|
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()
|
|
142
|
+
if(fields.phase==='failed'||kind==='client.error'||fields.phase==='start'&&['session.open','session.back','history.load','history.render','history.cache'].includes(kind))flush()
|
|
143
|
+
else if(!timer)timer=env.setTimeout?.(flush,500)
|
|
144
|
+
return row
|
|
145
|
+
}
|
|
146
|
+
function errorFacts(error){
|
|
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=[]
|
|
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])})}
|
|
149
|
+
return schema.facts({category,errorName:error?.name,frames,...(/^HTTP \d{3}$/.test(message)?{httpStatus:Number(message.slice(5))}:{})})
|
|
150
|
+
}
|
|
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})}}
|
|
152
|
+
function nativeSnapshot(){try{const value=JSON.parse(env.NativeBackground?.getBackgroundConfig?.()||'{}');return schema.facts({...value,httpStatus:value.lastHttpStatus})}catch{return {}}}
|
|
153
|
+
function configure(value){config=value;record('client.lifecycle',{status:env.document?.visibilityState==='hidden'?'hidden':'visible',...nativeSnapshot()});mount()}
|
|
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)})}
|
|
156
|
+
function text(){return JSON.stringify(report(),null,2)}
|
|
157
|
+
const label=(zh,en)=>env.I18N?.lang==='en'?en:zh
|
|
158
|
+
const $=id=>env.document?.getElementById(id)
|
|
159
|
+
function refreshPreview(){const node=$('fb-client-log-preview');if(node)node.textContent=text()}
|
|
160
|
+
function exportStatus(attempt=0){
|
|
161
|
+
const status=$('fb-client-log-status');let phase='error'
|
|
162
|
+
try{phase=env.NativeFile.getDiagnosticExportStatus()}catch{}
|
|
163
|
+
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.')
|
|
164
|
+
if(phase==='picking'&&attempt<120)exportTimer=env.setTimeout(()=>exportStatus(attempt+1),1000)
|
|
165
|
+
}
|
|
166
|
+
function download(){try{
|
|
167
|
+
if(env.NativeFile?.exportDiagnostics){if(!env.NativeFile.exportDiagnostics(text()))throw Error('export unavailable');if(exportTimer)env.clearTimeout(exportTimer);exportStatus();return}
|
|
168
|
+
if(env.NativeBackground)throw Error('native export unavailable')
|
|
169
|
+
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)
|
|
170
|
+
}catch{const status=$('fb-client-log-status');if(status)status.textContent=label('导出失败,请复制日志。','Export failed. Copy the report instead.')}}
|
|
171
|
+
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()}
|
|
172
|
+
function mount(){
|
|
173
|
+
const details=$('fb-client-log-details');if(!details||details.dataset.bound)return;details.dataset.bound='1'
|
|
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)
|
|
175
|
+
sheet=env.document.createElement('dialog');sheet.className='client-log-dialog';sheet.setAttribute('aria-labelledby','client-log-title')
|
|
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)
|
|
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']}
|
|
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)}}
|
|
179
|
+
translate();if(env.MutationObserver)new env.MutationObserver(translate).observe(env.document.documentElement,{attributes:true,attributeFilter:['lang']})
|
|
180
|
+
details.addEventListener('toggle',()=>{if(details.open)refreshPreview()})
|
|
181
|
+
$('fb-log-preview')?.addEventListener('click',refreshPreview)
|
|
182
|
+
$('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.')})
|
|
183
|
+
$('fb-log-export')?.addEventListener('click',download)
|
|
184
|
+
$('fb-log-clear')?.addEventListener('click',clear)
|
|
185
|
+
}
|
|
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
|
+
})
|
|
191
|
+
env.addEventListener?.('unhandledrejection',event=>record('client.error',{...errorFacts(event.reason),phase:'failed'}))
|
|
192
|
+
for(const status of ['online','offline'])env.addEventListener?.(status,()=>record('client.lifecycle',{status,online:status==='online'}))
|
|
193
|
+
env.document?.addEventListener('visibilitychange',()=>{record('client.lifecycle',{status:env.document.visibilityState==='visible'?'visible':'hidden',...nativeSnapshot()});flush()})
|
|
194
|
+
env.addEventListener?.('pagehide',flush)
|
|
195
|
+
function build(value){metadata={version:value?.version,buildId:value?.buildId}}
|
|
196
|
+
return {record,start,errorFacts,report,text,flush,clear,configure,show,download,build,nativeSnapshot,storageFailure,storageFacts,ready}
|
|
197
|
+
}
|
|
198
|
+
if(typeof module!=='undefined'&&module.exports)module.exports={createDiagnostics,createDiagnosticSchema}
|
|
199
|
+
else {
|
|
200
|
+
root.DshDiagnostics=createDiagnostics(root)
|
|
201
|
+
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{}
|
|
202
|
+
}
|
|
203
|
+
})(typeof window==='undefined'?globalThis:window)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/* Doctor entry for the authenticated host panel and gateway management page. */
|
|
2
|
+
'use strict'
|
|
3
|
+
;(function(root) {
|
|
4
|
+
const uuid=()=>globalThis.crypto?.randomUUID?.() || Date.now().toString(36)+'-'+Math.random().toString(36).slice(2)
|
|
5
|
+
const HANDOFF_KEY='dshRemoteDoctorHandoffV1'
|
|
6
|
+
function saveSessionHandoff(sessionId,token) {
|
|
7
|
+
const value=JSON.stringify({sessionId,token,origin:location.origin,at:Date.now()})
|
|
8
|
+
try { root.sessionStorage.setItem(HANDOFF_KEY,value);if(root.sessionStorage.getItem(HANDOFF_KEY)===value)return } catch {}
|
|
9
|
+
throw Error('无法保存本次连接,请在该主机的会话列表查看诊断结果。')
|
|
10
|
+
}
|
|
11
|
+
function restoreSessionConnection({state,newId=uuid,persist=()=>{}}) {
|
|
12
|
+
let raw
|
|
13
|
+
try { raw=root.sessionStorage.getItem(HANDOFF_KEY);root.sessionStorage.removeItem(HANDOFF_KEY) } catch { return false }
|
|
14
|
+
if(!raw)return false
|
|
15
|
+
let handoff
|
|
16
|
+
try { handoff=JSON.parse(raw) } catch { return false }
|
|
17
|
+
if(!handoff || typeof handoff!=='object' || Array.isArray(handoff))return false
|
|
18
|
+
const sessionId=new URL(location.href).searchParams.get('sessionId'),age=Date.now()-handoff.at
|
|
19
|
+
if(handoff.origin!==location.origin || !/^https?:$/.test(location.protocol) || !/^[a-zA-Z0-9_-]{1,200}$/.test(sessionId||'')
|
|
20
|
+
|| sessionId!==handoff.sessionId || !Number.isFinite(age) || age<0 || age>120000 || typeof handoff.token!=='string' || !handoff.token || handoff.token.length>4096)return false
|
|
21
|
+
// Adopt this explicit same-origin navigation without overwriting another
|
|
22
|
+
// saved identity or disabling the user's normal automatic selection policy.
|
|
23
|
+
let server=state.servers.find(row=>String(row.url||'').replace(/\/+$/,'')===handoff.origin && row.token===handoff.token)
|
|
24
|
+
if(!server){server={id:newId(),url:handoff.origin,token:handoff.token,note:'',group:state.activeGroup||'默认'};state.servers.unshift(server)}
|
|
25
|
+
const group=server.group||'默认'
|
|
26
|
+
if(!state.groups.includes(group))state.groups.push(group)
|
|
27
|
+
state.activeGroup=group;state.groupActive[group]=server.id
|
|
28
|
+
state.server=handoff.origin;state.token=handoff.token
|
|
29
|
+
persist()
|
|
30
|
+
return true
|
|
31
|
+
}
|
|
32
|
+
async function loadTarget({url=route=>route,headers={},connection={valid:()=>true},pluginMode=false}={}) {
|
|
33
|
+
if(!connection.valid())throw Error('Connection changed')
|
|
34
|
+
const response=await fetch(url(pluginMode?'/remote/admin/api/doctor-target':'/remote/api/doctor/target'),{headers,credentials:'same-origin',signal:AbortSignal.timeout(15000)})
|
|
35
|
+
if(!response.ok)throw Error('Target unavailable')
|
|
36
|
+
const text=await response.text()
|
|
37
|
+
if(!connection.valid() || text.length>512*1024)throw Error('Target unavailable')
|
|
38
|
+
return JSON.parse(text)
|
|
39
|
+
}
|
|
40
|
+
function open({state, pluginMode, token = () => '', copy, toast}) {
|
|
41
|
+
if(typeof root.DshDoctor?.open!=='function'){toast?.('诊疗组件未能加载,请刷新页面后重试。','err');return false}
|
|
42
|
+
const initial = state() || {}, identity = initial.hostname || location.host, savedToken = token()
|
|
43
|
+
const valid = () => !!state() && (state().hostname || location.host) === identity && token() === savedToken
|
|
44
|
+
async function rpc(method, payload) {
|
|
45
|
+
if (!valid()) throw new Error('Connection changed')
|
|
46
|
+
if (!['session.create','session.prompt'].includes(method)) throw new Error('Unsupported diagnosis operation')
|
|
47
|
+
const id = uuid()
|
|
48
|
+
const headers = {'content-type':'application/json','x-dsh-remote-client':'admin'}
|
|
49
|
+
if (!pluginMode) headers.authorization = 'Bearer ' + savedToken
|
|
50
|
+
const routes = pluginMode ? [method.replace('.', '/'), method] : [method]
|
|
51
|
+
for (const route of routes) {
|
|
52
|
+
const modern = route.includes('/')
|
|
53
|
+
const response = await fetch('/api/' + route, {method:'POST', credentials:'same-origin',headers,
|
|
54
|
+
body:JSON.stringify({type:'client-request',rpcId:id,method:route,payload:modern ? {args:{request:method==='session.prompt'?{...payload,requestId:payload.requestId||id}:payload}} : payload}),signal:AbortSignal.timeout(30000)})
|
|
55
|
+
if (!valid()) throw new Error('Connection changed')
|
|
56
|
+
if ([404,405,501].includes(response.status) && route !== routes.at(-1)) { await response.body?.cancel(); continue }
|
|
57
|
+
const body = await response.json()
|
|
58
|
+
if (!valid()) throw new Error('Connection changed')
|
|
59
|
+
if (!response.ok || body.result?.ok !== true) throw new Error('DSH diagnosis request failed (' + response.status + ')')
|
|
60
|
+
return body.result.value
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async function openSession(sessionId) {
|
|
64
|
+
if (!valid()) return
|
|
65
|
+
if (root.parent !== root) {
|
|
66
|
+
const requestId = uuid()
|
|
67
|
+
const opened = await new Promise(resolve=>{
|
|
68
|
+
const finish = value=>{clearTimeout(timer);root.removeEventListener('message',reply);resolve(value)}
|
|
69
|
+
const reply = event=>{if(event.source===root.parent && event.origin===location.origin && event.data?.source==='dsh-remote-host' && event.data.requestId===requestId)finish(event.data.opened===true)}
|
|
70
|
+
const timer=setTimeout(()=>finish(false),1500)
|
|
71
|
+
root.addEventListener('message',reply)
|
|
72
|
+
root.parent.postMessage({source:'dsh-remote-admin',type:'open-session',sessionId,requestId},location.origin)
|
|
73
|
+
})
|
|
74
|
+
if (opened) return
|
|
75
|
+
}
|
|
76
|
+
// Web host tabs can return to DSH's recent conversations. Gateway
|
|
77
|
+
// management tabs open the Remote conversation UI with a public ID only.
|
|
78
|
+
if(!valid())return
|
|
79
|
+
if (pluginMode) location.assign('/')
|
|
80
|
+
else { saveSessionHandoff(sessionId,savedToken);location.assign('/?sessionId=' + encodeURIComponent(sessionId)) }
|
|
81
|
+
}
|
|
82
|
+
root.DshDoctor.open({connection:{valid},rpc,openSession,surface:'management',copy,toast,
|
|
83
|
+
loadTarget:()=>loadTarget({pluginMode,connection:{valid},headers:pluginMode?{}:{authorization:'Bearer '+savedToken,'x-dsh-remote-client':'admin'}}),
|
|
84
|
+
environment:()=>({surface:pluginMode?'DSH plugin panel':'Gateway management',appVersion:state()?.version,gatewayVersion:state()?.gatewayVersion || state()?.version,dshVersion:state()?.dshVersion,
|
|
85
|
+
gatewayOk:state()?.mode==='gateway',gatewayReachable:state()?.upstream?.reachable,host:identity,mux:state()?.events?.mux?.connected?'connected':'unknown',hostEvents:state()?.events?.host?.connected?'connected':'unknown'})})
|
|
86
|
+
}
|
|
87
|
+
function consumeSessionLink(openSession, sessions) {
|
|
88
|
+
const url = new URL(location.href), id = url.searchParams.get('sessionId')
|
|
89
|
+
if (!id || !/^[a-zA-Z0-9_-]{1,200}$/.test(id) || !sessions.has(id)) return
|
|
90
|
+
url.searchParams.delete('sessionId');history.replaceState(null,'',url.pathname + url.search + url.hash)
|
|
91
|
+
void openSession(id)
|
|
92
|
+
}
|
|
93
|
+
root.DshDoctorEntry = {open,loadTarget,consumeSessionLink,restoreSessionConnection}
|
|
94
|
+
})(window)
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/* AI diagnosis entry. Uses only the shared --dsr-* theme variables. */
|
|
2
|
+
body.doctor-open { overflow: hidden; }
|
|
3
|
+
.doctor-overlay {
|
|
4
|
+
position: fixed;
|
|
5
|
+
inset: 0;
|
|
6
|
+
z-index: 90;
|
|
7
|
+
display: flex;
|
|
8
|
+
align-items: center;
|
|
9
|
+
justify-content: center;
|
|
10
|
+
padding: max(24px, var(--dsr-safe-top, 0px)) 24px max(24px, var(--dsr-safe-b, 0px));
|
|
11
|
+
box-sizing: border-box;
|
|
12
|
+
background: var(--dsr-overlay, rgba(3, 8, 16, .66));
|
|
13
|
+
overflow: auto;
|
|
14
|
+
}
|
|
15
|
+
.doctor-overlay.hidden { display: none !important; }
|
|
16
|
+
.doctor-overlay .doctor-card {
|
|
17
|
+
width: min(760px, 100%);
|
|
18
|
+
max-height: calc(100dvh - 48px);
|
|
19
|
+
box-sizing: border-box;
|
|
20
|
+
display: flex;
|
|
21
|
+
flex-direction: column;
|
|
22
|
+
gap: 0;
|
|
23
|
+
padding: 22px;
|
|
24
|
+
border: 1px solid var(--dsr-line, #30363d);
|
|
25
|
+
border-radius: 20px;
|
|
26
|
+
background: var(--dsr-panel, #161b22);
|
|
27
|
+
color: var(--dsr-text, #f0f6fc);
|
|
28
|
+
box-shadow: 0 24px 80px var(--dsr-shadow, rgba(0, 0, 0, .45));
|
|
29
|
+
overflow-y: auto;
|
|
30
|
+
overscroll-behavior: contain;
|
|
31
|
+
}
|
|
32
|
+
.doctor-overlay .doctor-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; }
|
|
33
|
+
.doctor-overlay .doctor-title { margin: 0; font-size: 21px; line-height: 1.35; }
|
|
34
|
+
.doctor-overlay .doctor-close {
|
|
35
|
+
flex: none;
|
|
36
|
+
width: 44px;
|
|
37
|
+
height: 44px;
|
|
38
|
+
margin: -8px -8px 0 0;
|
|
39
|
+
padding: 0;
|
|
40
|
+
border: 0;
|
|
41
|
+
border-radius: 12px;
|
|
42
|
+
color: var(--dsr-muted, #a7b0bc);
|
|
43
|
+
background: transparent;
|
|
44
|
+
font: inherit;
|
|
45
|
+
font-size: 25px;
|
|
46
|
+
line-height: 1;
|
|
47
|
+
cursor: pointer;
|
|
48
|
+
}
|
|
49
|
+
.doctor-overlay .doctor-close:hover, .doctor-overlay .doctor-close:focus-visible { color: var(--dsr-text, #f0f6fc); background: var(--dsr-panel-2, #21262d); }
|
|
50
|
+
.doctor-overlay .doctor-intro { margin: 8px 0 16px; color: var(--dsr-muted, #a7b0bc); font-size: 14px; line-height: 1.65; }
|
|
51
|
+
.doctor-overlay .doctor-notice {
|
|
52
|
+
margin: 0 0 16px;
|
|
53
|
+
padding: 13px 14px;
|
|
54
|
+
border: 1px solid var(--dsr-warning-line, #d2992266);
|
|
55
|
+
border-radius: 14px;
|
|
56
|
+
background: var(--dsr-warning-soft, #d299221f);
|
|
57
|
+
}
|
|
58
|
+
.doctor-overlay .doctor-notice strong { display: block; margin-bottom: 5px; color: var(--dsr-warning, #d29922); font-size: 13px; }
|
|
59
|
+
.doctor-overlay .doctor-notice p { margin: 0; font-size: 13px; line-height: 1.65; }
|
|
60
|
+
.doctor-overlay .doctor-notice .doctor-privacy { margin-top: 7px; color: var(--dsr-muted, #a7b0bc); font-size: 12px; }
|
|
61
|
+
.doctor-overlay .doctor-field { display: block; margin: 0 0 14px; }
|
|
62
|
+
.doctor-overlay .doctor-label { display: block; margin: 0 0 7px; color: var(--dsr-text, #f0f6fc); font-size: 13px; font-weight: 700; }
|
|
63
|
+
.doctor-overlay .doctor-env-label { margin-top: 2px; }
|
|
64
|
+
.doctor-overlay .doctor-textarea {
|
|
65
|
+
display: block;
|
|
66
|
+
width: 100%;
|
|
67
|
+
min-height: 116px;
|
|
68
|
+
max-height: 36dvh;
|
|
69
|
+
box-sizing: border-box;
|
|
70
|
+
padding: 12px 13px;
|
|
71
|
+
border: 1px solid var(--dsr-line, #30363d);
|
|
72
|
+
border-radius: 12px;
|
|
73
|
+
background: var(--dsr-bg, #0d1117);
|
|
74
|
+
color: var(--dsr-text, #f0f6fc);
|
|
75
|
+
font: inherit;
|
|
76
|
+
font-size: 14px;
|
|
77
|
+
line-height: 1.6;
|
|
78
|
+
resize: vertical;
|
|
79
|
+
}
|
|
80
|
+
.doctor-overlay .doctor-textarea:focus { border-color: var(--dsr-accent-line, #58a6ff66); outline: 2px solid var(--dsr-accent, #58a6ff); outline-offset: 2px; }
|
|
81
|
+
.doctor-overlay .doctor-textarea::placeholder { color: var(--dsr-muted, #a7b0bc); opacity: 1; }
|
|
82
|
+
.doctor-overlay .doctor-env { display: flex; flex-wrap: wrap; gap: 7px; margin: 0 0 14px; }
|
|
83
|
+
.doctor-overlay .doctor-env-item {
|
|
84
|
+
max-width: 100%;
|
|
85
|
+
padding: 5px 8px;
|
|
86
|
+
border: 1px solid var(--dsr-line, #30363d);
|
|
87
|
+
border-radius: 999px;
|
|
88
|
+
color: var(--dsr-muted, #a7b0bc);
|
|
89
|
+
background: var(--dsr-bg-2, #0d1117);
|
|
90
|
+
font-size: 11px;
|
|
91
|
+
line-height: 1.45;
|
|
92
|
+
overflow-wrap: anywhere;
|
|
93
|
+
}
|
|
94
|
+
.doctor-overlay .doctor-env-item b { color: var(--dsr-text, #f0f6fc); font-weight: 650; }
|
|
95
|
+
.doctor-overlay .doctor-muted { color: var(--dsr-muted, #a7b0bc); font-size: 12px; }
|
|
96
|
+
.doctor-overlay .doctor-include {
|
|
97
|
+
display: grid;
|
|
98
|
+
grid-template-columns: 20px minmax(0, 1fr);
|
|
99
|
+
gap: 3px 9px;
|
|
100
|
+
align-items: start;
|
|
101
|
+
margin: 0 0 14px;
|
|
102
|
+
padding: 11px 12px;
|
|
103
|
+
border: 1px solid var(--dsr-line, #30363d);
|
|
104
|
+
border-radius: 12px;
|
|
105
|
+
background: var(--dsr-bg-2, #0d1117);
|
|
106
|
+
cursor: pointer;
|
|
107
|
+
}
|
|
108
|
+
.doctor-overlay .doctor-include input { width: 18px; height: 18px; margin: 2px 0 0; accent-color: var(--dsr-accent, #58a6ff); }
|
|
109
|
+
.doctor-overlay .doctor-include span { font-size: 13px; line-height: 1.5; }
|
|
110
|
+
.doctor-overlay .doctor-include small { grid-column: 2; color: var(--dsr-muted, #a7b0bc); font-size: 11px; line-height: 1.55; }
|
|
111
|
+
.doctor-overlay .doctor-details {
|
|
112
|
+
margin: 0 0 12px;
|
|
113
|
+
border: 1px solid var(--dsr-line, #30363d);
|
|
114
|
+
border-radius: 12px;
|
|
115
|
+
background: var(--dsr-bg-2, #0d1117);
|
|
116
|
+
}
|
|
117
|
+
.doctor-overlay .doctor-details summary {
|
|
118
|
+
min-height: 44px;
|
|
119
|
+
box-sizing: border-box;
|
|
120
|
+
padding: 11px 12px;
|
|
121
|
+
color: var(--dsr-muted, #a7b0bc);
|
|
122
|
+
font-size: 12px;
|
|
123
|
+
line-height: 1.5;
|
|
124
|
+
cursor: pointer;
|
|
125
|
+
}
|
|
126
|
+
.doctor-overlay .doctor-details-body { padding: 0 12px 12px; }
|
|
127
|
+
.doctor-overlay .doctor-preview {
|
|
128
|
+
max-height: 210px;
|
|
129
|
+
margin: 0 0 10px;
|
|
130
|
+
padding: 11px;
|
|
131
|
+
border: 1px solid var(--dsr-line, #30363d);
|
|
132
|
+
border-radius: 10px;
|
|
133
|
+
background: var(--dsr-bg, #0d1117);
|
|
134
|
+
color: var(--dsr-muted, #a7b0bc);
|
|
135
|
+
font: 11px/1.55 ui-monospace, SFMono-Regular, Consolas, monospace;
|
|
136
|
+
white-space: pre-wrap;
|
|
137
|
+
overflow: auto;
|
|
138
|
+
overflow-wrap: anywhere;
|
|
139
|
+
}
|
|
140
|
+
.doctor-overlay .doctor-diagnostic-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
|
141
|
+
.doctor-overlay .doctor-status {
|
|
142
|
+
min-height: 20px;
|
|
143
|
+
margin: 2px 0 12px;
|
|
144
|
+
color: var(--dsr-muted, #a7b0bc);
|
|
145
|
+
font-size: 12px;
|
|
146
|
+
line-height: 1.55;
|
|
147
|
+
overflow-wrap: anywhere;
|
|
148
|
+
}
|
|
149
|
+
.doctor-overlay .doctor-status[data-kind="ok"] { color: var(--dsr-success, #3fb950); }
|
|
150
|
+
.doctor-overlay .doctor-status[data-kind="err"] { color: var(--dsr-error, #f85149); }
|
|
151
|
+
.doctor-overlay .doctor-status[data-kind="warn"] { color: var(--dsr-warning, #d29922); }
|
|
152
|
+
.doctor-overlay .doctor-status[data-kind="pending"] { color: var(--dsr-accent-strong, #58a6ff); }
|
|
153
|
+
.doctor-overlay .doctor-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; margin-top: auto; }
|
|
154
|
+
.doctor-overlay .doctor-btn {
|
|
155
|
+
min-height: 42px;
|
|
156
|
+
max-width: 100%;
|
|
157
|
+
padding: 9px 13px;
|
|
158
|
+
border: 1px solid var(--dsr-line, #30363d);
|
|
159
|
+
border-radius: 11px;
|
|
160
|
+
background: var(--dsr-panel-2, #21262d);
|
|
161
|
+
color: var(--dsr-text, #f0f6fc);
|
|
162
|
+
font: inherit;
|
|
163
|
+
font-size: 13px;
|
|
164
|
+
line-height: 1.35;
|
|
165
|
+
white-space: normal;
|
|
166
|
+
overflow-wrap: anywhere;
|
|
167
|
+
cursor: pointer;
|
|
168
|
+
}
|
|
169
|
+
.doctor-overlay .doctor-btn:hover:not(:disabled) { border-color: var(--dsr-accent-line, #58a6ff66); background: var(--dsr-accent-soft, #58a6ff1f); }
|
|
170
|
+
.doctor-overlay .doctor-btn.primary {
|
|
171
|
+
min-height: 44px;
|
|
172
|
+
margin-left: auto;
|
|
173
|
+
border-color: var(--dsr-accent-strong, #58a6ff);
|
|
174
|
+
background: var(--dsr-accent-strong, #58a6ff);
|
|
175
|
+
color: var(--dsr-on-accent, #07111f);
|
|
176
|
+
font-weight: 750;
|
|
177
|
+
}
|
|
178
|
+
.doctor-overlay .doctor-btn.primary:hover:not(:disabled) { filter: brightness(1.05); background: var(--dsr-accent-strong, #58a6ff); }
|
|
179
|
+
.doctor-overlay .doctor-btn.ghost { background: transparent; }
|
|
180
|
+
.doctor-overlay .doctor-btn.small { min-height: 36px; padding: 6px 10px; font-size: 12px; }
|
|
181
|
+
.doctor-overlay .doctor-btn:disabled { opacity: .45; cursor: default; }
|
|
182
|
+
.doctor-overlay :is(button, textarea, summary):focus-visible { outline: 2px solid var(--dsr-accent, #58a6ff); outline-offset: 2px; }
|
|
183
|
+
@media (max-width: 620px) {
|
|
184
|
+
.doctor-overlay { align-items: flex-end; padding: 0; }
|
|
185
|
+
.doctor-overlay .doctor-card {
|
|
186
|
+
max-height: 100dvh;
|
|
187
|
+
padding: 18px max(16px, var(--dsr-safe-r, 0px)) calc(18px + var(--dsr-safe-b, 0px)) max(16px, var(--dsr-safe-l, 0px));
|
|
188
|
+
border-radius: 20px 20px 0 0;
|
|
189
|
+
}
|
|
190
|
+
.doctor-overlay .doctor-title { font-size: 19px; }
|
|
191
|
+
.doctor-overlay .doctor-actions { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
|
192
|
+
.doctor-overlay .doctor-actions .doctor-btn.primary { grid-column: 1 / -1; margin-left: 0; }
|
|
193
|
+
.doctor-overlay .doctor-actions .doctor-btn.ghost { grid-column: 1 / -1; }
|
|
194
|
+
.doctor-overlay .doctor-preview { max-height: 160px; }
|
|
195
|
+
}
|
|
196
|
+
@media (prefers-reduced-motion: reduce) {
|
|
197
|
+
.doctor-overlay, .doctor-overlay .doctor-card, .doctor-overlay .doctor-btn { transition: none !important; }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/* Scoped AI panel */
|
|
201
|
+
.doctor-overlay [hidden]{display:none!important}
|
|
202
|
+
.doctor-overlay .doctor-card{margin:0}
|
|
203
|
+
.doctor-overlay .doctor-head{width:auto;padding:0;border:0;background:transparent;cursor:default;font:inherit;text-align:left;color:inherit}
|
|
204
|
+
.doctor-overlay .doctor-target-select{width:100%;min-height:44px;padding:9px;border:1px solid var(--dsr-line);border-radius:8px;background:var(--dsr-bg);color:var(--dsr-text);font:inherit}
|
|
205
|
+
.doctor-overlay .doctor-target-path{display:block;overflow-wrap:anywhere;font-size:12px}
|