dsh-remote-plugin 0.8.0-rc.3 → 0.8.0-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apk/dsh-remote.apk +0 -0
- package/gateway.cjs +305 -33
- package/index.mjs +24 -0
- package/package.json +3 -1
- package/peak-reminders.mjs +47 -0
- package/public/announcement-forms.js +89 -0
- package/public/app.js +381 -138
- package/public/build.json +5 -0
- package/public/desktop/desktop.html +11 -0
- package/public/desktop/desktop.js +156 -50
- package/public/diagnostics.js +109 -0
- package/public/extensions.js +4 -2
- package/public/history.js +15 -8
- package/public/index.html +21 -4
- package/public/network.js +1 -1
- package/public/operations.js +1 -1
- package/public/teams.js +76 -0
- package/public/turn-results.js +119 -0
- package/public/update.json +4 -4
- package/public/version.json +1 -1
- package/public/workflow.css +39 -0
- package/public/workflow.js +3 -1
- package/teams.mjs +53 -0
|
@@ -417,6 +417,12 @@
|
|
|
417
417
|
<input id="fb-contact" class="ds-fb-input" maxlength="200" data-i18n-placeholder="ds.feedbackContactPlaceholder" placeholder="联系方式(可选):邮箱 / 微信 / B站 ID">
|
|
418
418
|
<label class="ds-fb-diagnostics"><input id="fb-include-diagnostics" type="checkbox"> <span data-i18n="ds.feedbackIncludeDiagnostics">附带兼容性诊断日志(可选)</span><small data-i18n="ds.feedbackDiagnosticsPrivacy">仅上传网关/协议版本、接口失败摘要和实时链路状态;不包含令牌、Cookie、对话内容或文件路径。</small></label>
|
|
419
419
|
<label class="ds-fb-diagnostics"><input id="fb-include-crashes" type="checkbox"> <span data-i18n="ds.feedbackIncludeCrashes">附带崩溃日志摘要(可选)</span><small data-i18n="ds.feedbackCrashPrivacy">默认仅在本机记录。勾选后上传最近 3 条退出、重启和错误位置摘要,不含对话、密钥或完整路径。</small></label>
|
|
420
|
+
<section class="client-diagnostics" aria-label="操作诊断日志">
|
|
421
|
+
<p data-log-label="privacy">操作日志仅保存在此设备,记录操作阶段、耗时、错误位置与连接状态。可复制或导出后自行反馈。</p>
|
|
422
|
+
<details id="fb-client-log-details"><summary data-log-label="details">查看操作诊断日志</summary><pre id="fb-client-log-preview"></pre></details>
|
|
423
|
+
<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>
|
|
424
|
+
<p id="fb-client-log-status" role="status" aria-live="polite"></p>
|
|
425
|
+
</section>
|
|
420
426
|
<details id="fb-crash-details" class="crash-preview"><summary data-i18n="ds.feedbackCrashPreview">查看拟上传的日志摘要</summary><pre id="fb-crash-preview"></pre></details>
|
|
421
427
|
</div>
|
|
422
428
|
<div class="ds-modal-actions">
|
|
@@ -588,6 +594,7 @@
|
|
|
588
594
|
'ds.toastSent': '已发送', 'ds.toastCopied': '令牌已复制', 'ds.toastAuth': '令牌无效',
|
|
589
595
|
'ds.toastConnFailed': '连接失败', 'ds.toastOpFailed': '操作失败',
|
|
590
596
|
'ds.sessionsEmpty': '暂无会话', 'ds.loading': '加载中…',
|
|
597
|
+
'ds.historyRenderFailed': '部分记录显示失败,请重试',
|
|
591
598
|
'ds.historyCached': '本地缓存', 'ds.historySyncing': '本地缓存 · 正在同步', 'ds.historySynced': '最新记录已同步', 'ds.historySaved': '最新记录 · 已缓存', 'ds.historyOffline': '本地记录 · 网络不可用', 'ds.historyEarlier': '加载更早的记录', 'ds.historyLoadingEarlier': '正在加载更早的记录…', 'ds.historyLatest': '回到最新', 'ds.historyCacheFailed': '已同步 · 本地缓存未保存', 'ds.historyLoading': '加载历史…', 'ds.historyEmpty': '暂无消息', 'ds.historyRetry': '重试',
|
|
592
599
|
'ds.allow': '允许', 'ds.reject': '拒绝',
|
|
593
600
|
'ds.approvalTitle': '工具审批', 'ds.questionNotify': '需要回答',
|
|
@@ -699,6 +706,7 @@
|
|
|
699
706
|
'ds.toastSent': 'Sent', 'ds.toastCopied': 'Token copied', 'ds.toastAuth': 'Invalid token',
|
|
700
707
|
'ds.toastConnFailed': 'Connection failed', 'ds.toastOpFailed': 'Operation failed',
|
|
701
708
|
'ds.sessionsEmpty': 'No sessions', 'ds.loading': 'Loading…',
|
|
709
|
+
'ds.historyRenderFailed': 'Some records could not be displayed. Retry.',
|
|
702
710
|
'ds.historyCached': 'Local cache', 'ds.historySyncing': 'Local cache · Syncing', 'ds.historySynced': 'Latest history synced', 'ds.historySaved': 'Latest history · Cached', 'ds.historyOffline': 'Local history · Offline', 'ds.historyEarlier': 'Load earlier history', 'ds.historyLoadingEarlier': 'Loading earlier history…', 'ds.historyLatest': 'Jump to latest', 'ds.historyCacheFailed': 'Synced · Cache could not be saved', 'ds.historyLoading': 'Loading history…', 'ds.historyEmpty': 'No messages yet', 'ds.historyRetry': 'Retry',
|
|
703
711
|
'ds.allow': 'Allow', 'ds.reject': 'Reject',
|
|
704
712
|
'ds.approvalTitle': 'Tool approval', 'ds.questionNotify': 'Question',
|
|
@@ -781,10 +789,13 @@
|
|
|
781
789
|
<script src="../plugin-center.js"></script>
|
|
782
790
|
<script src="../skills.js"></script>
|
|
783
791
|
<script src="../insights.js"></script>
|
|
792
|
+
<script src="../teams.js"></script>
|
|
784
793
|
<script src="../extensions.js"></script>
|
|
785
794
|
<script src="../sha256.js"></script>
|
|
795
|
+
<script src="../diagnostics.js"></script>
|
|
786
796
|
<script src="../history.js"></script>
|
|
787
797
|
<script src="../activity.js"></script>
|
|
798
|
+
<script src="../turn-results.js"></script>
|
|
788
799
|
<script src="../image-preview.js"></script>
|
|
789
800
|
<script src="../link-check.js"></script>
|
|
790
801
|
<script src="../network.js"></script>
|
|
@@ -591,18 +591,21 @@ async function submitFeedback() {
|
|
|
591
591
|
if (message.length > 2000) { toast(t('ds.feedbackTooLong'), 'err'); return }
|
|
592
592
|
const btn = $('fb-submit')
|
|
593
593
|
btn.disabled = true
|
|
594
|
+
const diagnostic=globalThis.DshDiagnostics?.start('feedback.submit')
|
|
594
595
|
try {
|
|
595
596
|
const res = await fetch(apiUrl('/feedback'), {
|
|
596
597
|
method: 'POST',
|
|
597
598
|
headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token },
|
|
598
599
|
body: JSON.stringify({ type, message, contact, appVersion: '', includeDiagnostics, includeCrashLogs })
|
|
599
600
|
})
|
|
601
|
+
diagnostic?.end({phase:res.ok?'complete':'failed',httpStatus:res.status})
|
|
600
602
|
let json = {}
|
|
601
603
|
try { json = await res.json() } catch {}
|
|
602
604
|
if (res.ok && json.ok) { toast(t('ds.feedbackSubmitted'), 'ok'); closeFeedbackModal() }
|
|
603
605
|
else if (res.status === 429) { toast(t('ds.feedbackRateLimited'), 'err') }
|
|
604
606
|
else { toast(t('ds.feedbackSubmitFailed', { msg: json.error || res.status }), 'err') }
|
|
605
|
-
} catch {
|
|
607
|
+
} catch(error) {
|
|
608
|
+
diagnostic?.fail(error)
|
|
606
609
|
toast(t('ds.feedbackSubmitFailed', { msg: t('ds.feedbackNetworkError') }), 'err')
|
|
607
610
|
} finally {
|
|
608
611
|
btn.disabled = false
|
|
@@ -630,20 +633,19 @@ function apiUrl(path) { return (state.server || '') + path }
|
|
|
630
633
|
let wsTicketPromise = null
|
|
631
634
|
let wsTicketConnection = null
|
|
632
635
|
async function getWsTicket() {
|
|
633
|
-
|
|
634
|
-
if (state.wsTicket.token === state.token && state.wsTicket.server === state.server &&
|
|
635
|
-
state.wsTicket.value && state.wsTicket.expiresAt > now + 15000) return state.wsTicket.value
|
|
636
|
+
// Only share an in-flight request; never reuse a previous handshake ticket.
|
|
636
637
|
if (wsTicketPromise && wsTicketConnection?.valid()) return wsTicketPromise
|
|
637
638
|
const connection = captureConnection()
|
|
638
639
|
const token = state.token
|
|
639
640
|
const server = state.server
|
|
640
641
|
const job = (async () => {
|
|
641
|
-
if (activeGatewayCapability('wsTicket') === false) throw new Error('ws ticket unsupported')
|
|
642
|
+
if (activeGatewayCapability('wsTicket') === false) throw Object.assign(new Error('ws ticket unsupported'), { unsupported: true })
|
|
642
643
|
const res = await fetch(apiUrl('/api/ws-ticket'), {
|
|
643
644
|
method: 'POST',
|
|
645
|
+
signal: AbortSignal.timeout(8000),
|
|
644
646
|
headers: { authorization: 'Bearer ' + token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
|
|
645
647
|
})
|
|
646
|
-
if (!res.ok) throw new Error('ws ticket HTTP ' + res.status)
|
|
648
|
+
if (!res.ok) throw Object.assign(new Error('ws ticket HTTP ' + res.status), { unsupported: [404, 405, 501].includes(res.status) })
|
|
647
649
|
const data = await res.json()
|
|
648
650
|
if (!connection.valid()) throw new Error('stale ws ticket')
|
|
649
651
|
if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
|
|
@@ -655,6 +657,8 @@ async function getWsTicket() {
|
|
|
655
657
|
try { return await job } finally { if (wsTicketPromise === job) { wsTicketPromise = null; wsTicketConnection = null } }
|
|
656
658
|
}
|
|
657
659
|
async function rpc(method, payload = {}, timeoutMs = 45000) {
|
|
660
|
+
const diagnostic=globalThis.DshDiagnostics?.start('rpc',{method,sessionId:payload.sessionId,server:state.server})
|
|
661
|
+
try {
|
|
658
662
|
const opts = {
|
|
659
663
|
method: 'POST',
|
|
660
664
|
headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
|
|
@@ -667,6 +671,7 @@ async function rpc(method, payload = {}, timeoutMs = 45000) {
|
|
|
667
671
|
const connection = operation ? captureConnection() : null
|
|
668
672
|
const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
|
|
669
673
|
const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
|
|
674
|
+
diagnostic?.end({phase:'response',httpStatus:res.status})
|
|
670
675
|
if (res.status === 401) throw new Error('AUTH')
|
|
671
676
|
if (!res.ok) throw new Error('HTTP ' + res.status)
|
|
672
677
|
const full = await res.json()
|
|
@@ -677,7 +682,9 @@ async function rpc(method, payload = {}, timeoutMs = 45000) {
|
|
|
677
682
|
error.code = err.code
|
|
678
683
|
throw error
|
|
679
684
|
}
|
|
685
|
+
diagnostic?.end({phase:'complete'})
|
|
680
686
|
return full.result.value
|
|
687
|
+
} catch(error) { diagnostic?.fail(error);throw error }
|
|
681
688
|
}
|
|
682
689
|
async function respond(rpcId, value) {
|
|
683
690
|
const opts = {
|
|
@@ -728,8 +735,6 @@ async function refreshHostDescriptionDesktop({ notify = false } = {}) {
|
|
|
728
735
|
const host = await rpc('host.describe', {}, 5000)
|
|
729
736
|
if (!connection.valid()) return null
|
|
730
737
|
state.hostInfo = host
|
|
731
|
-
const health = activeGatewayHealth()
|
|
732
|
-
if (health) health.upstreamReachable = true
|
|
733
738
|
hostDescribeFailures = 0
|
|
734
739
|
if (hostDescribeRetryTimer) clearTimeout(hostDescribeRetryTimer)
|
|
735
740
|
hostDescribeRetryTimer = null
|
|
@@ -868,8 +873,9 @@ function activeGatewayHealth() {
|
|
|
868
873
|
|
|
869
874
|
function dshReachable() {
|
|
870
875
|
const health = activeGatewayHealth()
|
|
876
|
+
if (health && typeof health.upstreamOk === 'boolean') return health.upstreamOk
|
|
871
877
|
if (health && typeof health.upstreamReachable === 'boolean') return health.upstreamReachable
|
|
872
|
-
return !!state.hostInfo
|
|
878
|
+
return !!state.hostInfo && state.hostInfo.metadataOnly !== true
|
|
873
879
|
}
|
|
874
880
|
async function selectFastestServer({ silent = false, reconnect = true } = {}) {
|
|
875
881
|
const request = selectFastestServer.request = (selectFastestServer.request || 0) + 1
|
|
@@ -1265,12 +1271,25 @@ function openStreams() {
|
|
|
1265
1271
|
function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
1266
1272
|
if (!state.token) return
|
|
1267
1273
|
if (ticket === null) {
|
|
1268
|
-
|
|
1274
|
+
if (streams[kind] && [WebSocket.OPEN, WebSocket.CONNECTING].includes(streams[kind].readyState)) return
|
|
1275
|
+
const connection=captureConnection(), generation=streamMeta[kind].generation
|
|
1276
|
+
const valid=()=>connection.valid() && generation===streamMeta[kind].generation
|
|
1269
1277
|
void getWsTicket().then((value) => {
|
|
1270
|
-
if (
|
|
1271
|
-
}).catch(() => {
|
|
1278
|
+
if (valid()) openStream(kind, handler, refreshOnOpen, isRestore, value)
|
|
1279
|
+
}).catch((error) => {
|
|
1272
1280
|
// 兼容旧网关/插件副本: ticket 接口不可用时临时回退旧 token 握手。
|
|
1273
|
-
if (
|
|
1281
|
+
if (!valid()) return
|
|
1282
|
+
if (error.unsupported) openStream(kind, handler, refreshOnOpen, isRestore, '')
|
|
1283
|
+
else {
|
|
1284
|
+
clearStreamRetry(kind)
|
|
1285
|
+
const meta = streamMeta[kind]
|
|
1286
|
+
meta.failures++
|
|
1287
|
+
aggregateStreamFailures()
|
|
1288
|
+
if (state.streamMode !== 'poll' && meta.failures >= 3) { enterPollMode(); return }
|
|
1289
|
+
const delay = Math.round(Math.min(1500 * 2 ** Math.min(meta.attempt++, 6), 60000) * (0.8 + Math.random() * 0.4))
|
|
1290
|
+
meta.retryTimer = setTimeout(() => { meta.retryTimer = null; if (valid() && navigator.onLine) openStream(kind, handler, refreshOnOpen, isRestore) }, delay)
|
|
1291
|
+
setReconnect(delay)
|
|
1292
|
+
}
|
|
1274
1293
|
})
|
|
1275
1294
|
return
|
|
1276
1295
|
}
|
|
@@ -1298,6 +1317,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1298
1317
|
ws._isRestore = !!isRestore
|
|
1299
1318
|
ws.onopen = () => {
|
|
1300
1319
|
if (!streamIsCurrent(kind, ws, generation)) return
|
|
1320
|
+
globalThis.DshDiagnostics?.record('stream.state',{channel:kind,status:'open',attempt:meta.failures})
|
|
1301
1321
|
state.streamsOk[kind] = true
|
|
1302
1322
|
markStreamInfo(kind, { status: 'open', lastOpenAt: Date.now(), lastCloseCode: 0, lastCloseReason: '' })
|
|
1303
1323
|
meta.attempt = 0
|
|
@@ -1326,7 +1346,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1326
1346
|
updateConn()
|
|
1327
1347
|
try { handler(JSON.parse(msg.data)) } catch {}
|
|
1328
1348
|
}
|
|
1329
|
-
ws.onclose = () => {
|
|
1349
|
+
ws.onclose = (event) => {
|
|
1330
1350
|
clearStreamTimers(ws)
|
|
1331
1351
|
if (!streamIsCurrent(kind, ws, generation)) return
|
|
1332
1352
|
streams[kind] = null
|
|
@@ -1334,9 +1354,10 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1334
1354
|
markStreamInfo(kind, {
|
|
1335
1355
|
status: 'closed',
|
|
1336
1356
|
lastCloseAt: Date.now(),
|
|
1337
|
-
lastCloseCode: Number(
|
|
1338
|
-
lastCloseReason: String(
|
|
1357
|
+
lastCloseCode: Number(event.code) || 0,
|
|
1358
|
+
lastCloseReason: String(event.reason || '').slice(0, 200),
|
|
1339
1359
|
})
|
|
1360
|
+
globalThis.DshDiagnostics?.record('stream.state',{channel:kind,status:'closed',closeCode:Number(event.code)||0,attempt:meta.failures+1})
|
|
1340
1361
|
meta.failures++
|
|
1341
1362
|
aggregateStreamFailures()
|
|
1342
1363
|
updateConn()
|
|
@@ -1348,6 +1369,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1348
1369
|
const attempt = meta.attempt++
|
|
1349
1370
|
const baseDelay = Math.min(1500 * Math.pow(2, attempt), 60000)
|
|
1350
1371
|
const delay = Math.round(baseDelay * (0.8 + Math.random() * 0.4))
|
|
1372
|
+
globalThis.DshDiagnostics?.record('stream.retry',{channel:kind,attempt:meta.attempt,delayMs:delay})
|
|
1351
1373
|
setReconnect(delay)
|
|
1352
1374
|
clearStreamRetry(kind)
|
|
1353
1375
|
meta.retryTimer = setTimeout(() => {
|
|
@@ -1360,6 +1382,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1360
1382
|
|
|
1361
1383
|
/* ---------------- 轮询降级模式 ---------------- */
|
|
1362
1384
|
function enterPollMode() {
|
|
1385
|
+
globalThis.DshDiagnostics?.record('poll.state',{status:'poll'})
|
|
1363
1386
|
if (state.streamMode === 'poll') return
|
|
1364
1387
|
state.streamMode = 'poll'
|
|
1365
1388
|
state.pollSeq = { mux: 0, host: 0 }
|
|
@@ -1490,6 +1513,7 @@ function onMuxFrame(full) {
|
|
|
1490
1513
|
if (f.type === 'session/queue') { state.queues[f.sessionId] = f.items || []; renderQueue(); return }
|
|
1491
1514
|
if (f.type === 'session/projection') { applyProjection(f.sessionId, f.key, f.value, f.seq); return }
|
|
1492
1515
|
if (f.type === 'stream/error') toast(f.error?.message || 'stream error', 'err')
|
|
1516
|
+
if (f.type === 'session/stream-error' && f.sessionId === state.current) { const message=f.error?.code==='session/migration-required'?t('session.migrationRequired'):f.error?.message;setSessionRecovery('error',message);toast(message,'err') }
|
|
1493
1517
|
}
|
|
1494
1518
|
function onHostFrame(full) {
|
|
1495
1519
|
const f = full.payload
|
|
@@ -1725,7 +1749,8 @@ function sessionLabelOf(s) {
|
|
|
1725
1749
|
return `${title} · ${String(s.sessionId).slice(-8)}`
|
|
1726
1750
|
}
|
|
1727
1751
|
function isTopLevelSession(session) {
|
|
1728
|
-
|
|
1752
|
+
// Ordinary forks also carry parentSessionId; only explicit subagents leave the main list.
|
|
1753
|
+
return !!session && session.origin !== 'subagent'
|
|
1729
1754
|
}
|
|
1730
1755
|
// DSH marks sessions created via "new session" but never prompted as blank and hides
|
|
1731
1756
|
// them in its own UI; keep the same semantics here so they do not occupy the list,
|
|
@@ -1956,6 +1981,7 @@ async function archiveEmptySessionOnLeave(sessionId, leaving = false) {
|
|
|
1956
1981
|
}
|
|
1957
1982
|
|
|
1958
1983
|
async function openSession(id) {
|
|
1984
|
+
globalThis.DshDiagnostics?.record('session.open',{phase:'start',sessionId:id,server:state.server})
|
|
1959
1985
|
if (state.current && state.current !== id) void archiveEmptySessionOnLeave(state.current,true)
|
|
1960
1986
|
state.current = id
|
|
1961
1987
|
setSessionRecovery('loading')
|
|
@@ -1973,26 +1999,34 @@ async function openSession(id) {
|
|
|
1973
1999
|
renderSessionPendingDesktop()
|
|
1974
2000
|
updateComposerStatus()
|
|
1975
2001
|
void refreshCompactionStatus(id)
|
|
1976
|
-
await restoreCachedHistory()
|
|
2002
|
+
try { const restored=await restoreCachedHistory();globalThis.DshDiagnostics?.record('history.cache',{phase:restored?'hit':'miss',sessionId:id}) } catch(error) {
|
|
2003
|
+
globalThis.DshDiagnostics?.record('history.cache',{phase:'failed',sessionId:id,...globalThis.DshDiagnostics.errorFacts(error)})
|
|
2004
|
+
if(state.current!==id||state.history!==openingHistory||!openingConnection.valid())return
|
|
2005
|
+
// A broken local cache must not prevent fetching the authoritative history.
|
|
2006
|
+
Object.assign(openingHistory,emptyDesktopHistory())
|
|
2007
|
+
getConversationView().reset()
|
|
2008
|
+
}
|
|
1977
2009
|
if(state.current!==id||state.history!==openingHistory||!openingConnection.valid())return
|
|
1978
2010
|
await loadHistory()
|
|
1979
2011
|
}
|
|
1980
2012
|
async function closeSession() {
|
|
2013
|
+
globalThis.DshDiagnostics?.record('session.back',{phase:'start',sessionId:state.current,loading:state.history.loading,loaded:state.history.loaded,renderErrors:state.history.renderError?1:0})
|
|
1981
2014
|
const sessionId = state.current
|
|
1982
2015
|
const parentId = state.byId.get(sessionId)?.parentSessionId
|
|
1983
2016
|
if (parentId && parentId !== sessionId) return openSession(parentId)
|
|
1984
|
-
|
|
1985
|
-
if (state.current !== sessionId) return
|
|
2017
|
+
const cleanup=sessionId&&state.history.loaded&&!state.history.loading&&!state.history.renderError
|
|
1986
2018
|
state.current = null
|
|
1987
2019
|
setSessionRecovery('idle')
|
|
1988
2020
|
state.history = emptyDesktopHistory()
|
|
2021
|
+
showView('view-sessions')
|
|
2022
|
+
globalThis.DshDiagnostics?.record('session.back',{phase:'navigate',sessionId})
|
|
1989
2023
|
const cards = $('session-cards')
|
|
1990
2024
|
if (cards) cards.innerHTML = ''
|
|
1991
2025
|
renderQueue()
|
|
1992
2026
|
renderSessionPendingDesktop()
|
|
1993
2027
|
updateComposerStatus()
|
|
1994
2028
|
updateSessionActions()
|
|
1995
|
-
|
|
2029
|
+
if(cleanup)await archiveEmptySessionOnLeave(sessionId,true)
|
|
1996
2030
|
}
|
|
1997
2031
|
|
|
1998
2032
|
function restoreCachedSessionList() {
|
|
@@ -2005,12 +2039,14 @@ function historyCacheScope() { const hash=new SHA256();hash.update(new TextEncod
|
|
|
2005
2039
|
function historySource(value) {
|
|
2006
2040
|
state.history.source=value
|
|
2007
2041
|
const el=$('history-source')
|
|
2008
|
-
if(el)el.textContent=t(({cache:'ds.historyCached',syncing:'ds.historySyncing',synced:'ds.historySynced',saved:'ds.historySaved',offline:'ds.historyOffline',saveFailed:'ds.historyCacheFailed'})[value]||'ds.historySynced')
|
|
2042
|
+
if(el)el.textContent=t(({cache:'ds.historyCached',syncing:'ds.historySyncing',synced:'ds.historySynced',saved:'ds.historySaved',offline:'ds.historyOffline',saveFailed:'ds.historyCacheFailed',error:'ds.historyRenderFailed'})[value]||'ds.historySynced')
|
|
2009
2043
|
}
|
|
2010
2044
|
function getConversationView() {
|
|
2011
2045
|
if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
|
|
2012
2046
|
html:entry=>eventHtml(entry),
|
|
2047
|
+
errorLabel:()=>t('ds.historyRenderFailed'),
|
|
2013
2048
|
older:()=>loadHistory(false),olderLabel:()=>t('ds.historyEarlier'),loadingLabel:()=>t('ds.historyLoadingEarlier'),live:partialReasoningHtml,
|
|
2049
|
+
retry:()=>loadHistory(true),retryLabel:()=>t('ds.historyRetry'),unreadableLabel:()=>I18N.lang==='en'?'No displayable messages on this page. Load earlier records or retry. If DSH reports a migration failure, open the original session in DSH.':'本页历史没有可显示的消息,请加载更早记录或重试。如提示格式迁移失败,请先在 DSH 中打开原会话。',
|
|
2014
2050
|
changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end;const latest=$('btn-history-latest');if(latest){latest.classList.toggle('hidden',view.atBottom&&view.unread===0&&!state.history.tailEvicted);latest.textContent=t('ds.historyLatest')+(view.unread?' ('+view.unread+')':view.hasPending?' · '+(I18N.lang==='en'?'New content':'有新内容'):'')}},
|
|
2015
2051
|
scrolled:()=>{}
|
|
2016
2052
|
})
|
|
@@ -2051,6 +2087,7 @@ function trimVisible(direction='tail') {
|
|
|
2051
2087
|
async function loadHistory(reset = true) {
|
|
2052
2088
|
const connection=captureConnection(),id=state.current,history=state.history
|
|
2053
2089
|
if(!id||history.loading||(!reset&&Date.now()<(history.retryAfter||0)))return
|
|
2090
|
+
const diagnostic=globalThis.DshDiagnostics?.start('history.load',{sessionId:id,server:state.server,reset,cached:!!history.cached,count:history.visible.length})
|
|
2054
2091
|
const reasoningVersion=history.reasoningVersion||0,hadContent=history.visible.length>0
|
|
2055
2092
|
history.loading=true
|
|
2056
2093
|
if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
|
|
@@ -2062,42 +2099,62 @@ async function loadHistory(reset = true) {
|
|
|
2062
2099
|
getConversationView().more.disabled=true
|
|
2063
2100
|
getConversationView().more.textContent=getConversationView().options.loadingLabel()
|
|
2064
2101
|
let v
|
|
2065
|
-
|
|
2066
|
-
|
|
2102
|
+
// Contain preparation and final DOM failures as well as network errors. Reset
|
|
2103
|
+
// the view before replacing its DOM so an identical retry cannot reuse stale nodes.
|
|
2104
|
+
const failLoad = (error,renderFailure=false) => {
|
|
2105
|
+
diagnostic?.fail(error)
|
|
2067
2106
|
history.loading=false;history.retryAfter=Date.now()+1500
|
|
2068
2107
|
if(error.message==='AUTH'){return}
|
|
2069
|
-
if(hadContent){historySource('offline');setSessionRecovery('cached',error.message);
|
|
2108
|
+
if(hadContent&&!renderFailure){try{renderHistory(false,'fixed');history.renderError=!!getConversationView().renderErrors;historySource(history.renderError?'error':'offline');setSessionRecovery(history.renderError?'error':'cached',error.message);return}catch{}}
|
|
2109
|
+
history.renderError=true;historySource('error')
|
|
2070
2110
|
setSessionRecovery('error',error.message)
|
|
2111
|
+
getConversationView().reset?.()
|
|
2071
2112
|
$('history').innerHTML='<div class="history-empty">'+esc(error.message)+'</div>'
|
|
2072
2113
|
const retry=document.createElement('button');retry.type='button';retry.className='history-page-control';retry.textContent=t('ds.historyRetry');retry.addEventListener('click',()=>{void loadHistory(true)});$('history').append(retry)
|
|
2114
|
+
}
|
|
2115
|
+
try{v=await rpc('session.history',payload,network.readTimeout);globalThis.DshDiagnostics?.record('history.load',{phase:'response',traceId:diagnostic?.traceId,sessionId:id,rawCount:Array.isArray(v?.events)?v.events.length:0})}catch(error){
|
|
2116
|
+
if(!connection.valid()||state.current!==id||state.history!==history)return
|
|
2117
|
+
failLoad(error)
|
|
2073
2118
|
return
|
|
2074
2119
|
}
|
|
2075
2120
|
if(!connection.valid()||state.current!==id||state.history!==history)return
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
const
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2121
|
+
let liveReasoning, rawSeqs, floor
|
|
2122
|
+
try {
|
|
2123
|
+
liveReasoning=(history.reasoningVersion||0)!==reasoningVersion?new Map(history.partialReasoning):null
|
|
2124
|
+
hydrateSessionProjections(id,v.projections);history.loaded=true
|
|
2125
|
+
const incoming=v.events||[],prepared=[]
|
|
2126
|
+
for (const entry of incoming) {
|
|
2127
|
+
const ev=entry?.event
|
|
2128
|
+
applyReasoningStreamEvent(ev)
|
|
2129
|
+
if(ev?.type==='turn/start'||ev?.type==='turn/end')noteSessionTurnTime(id,ev)
|
|
2130
|
+
if(ev?.seq==null||!shouldShowEvent(ev.type,ev))continue
|
|
2131
|
+
prepared.push({seq:ev.seq,event:ev,view:entry.view})
|
|
2132
|
+
}
|
|
2133
|
+
rawSeqs=incoming.map(entry=>entry?.event?.seq).filter(Number.isFinite);floor=rawSeqs.length?Math.min(...rawSeqs):Infinity
|
|
2134
|
+
if(reset){const retainedOlder=!!v.hasMore&&history.visible.some(entry=>entry.seq<floor);const ceiling=rawSeqs.length?Math.max(...rawSeqs)+1:Infinity;history.visible=rawSeqs.length?window.DshHistory.reconcile(history.visible,prepared,floor,!!v.hasMore,ceiling):[];history.minSeq=retainedOlder?Math.min(history.minSeq,floor):floor;history.tailEvicted=false}
|
|
2135
|
+
else{history.visible=window.DshHistory.reconcile(history.visible,prepared,floor,true,payload.beforeSeq);history.minSeq=Math.min(history.minSeq,floor)}
|
|
2136
|
+
history.seqs=new Set(history.visible.map(entry=>entry.seq));history.headEvicted=false;trimVisible(reset?'tail':'older')
|
|
2137
|
+
if(liveReasoning)history.partialReasoning=liveReasoning;else applyReasoningBaseline(v.partialReasoning)
|
|
2138
|
+
history.hasMore=(!!v.hasMore||(reset&&history.headEvicted)) && rawSeqs.length>0 && (reset || floor<payload.beforeSeq)
|
|
2139
|
+
} catch (error) {
|
|
2140
|
+
failLoad(error)
|
|
2141
|
+
return
|
|
2142
|
+
}
|
|
2143
|
+
try {
|
|
2144
|
+
history.loading=false;history.cached=false
|
|
2145
|
+
updateSessionActions();renderSessionCards()
|
|
2146
|
+
globalThis.DshDiagnostics?.record('history.render',{phase:'start',traceId:diagnostic?.traceId,sessionId:id,count:history.visible.length})
|
|
2147
|
+
renderHistory(!hadContent,reset?'fixed':'keep')
|
|
2148
|
+
history.renderError=!!getConversationView().renderErrors
|
|
2149
|
+
historySource(history.renderError?'error':'synced');setSessionRecovery(history.renderError?'error':'ready')
|
|
2150
|
+
diagnostic?.end({phase:history.renderError?'failed':'rendered',count:history.visible.length,renderedCount:getConversationView().end-getConversationView().start,renderErrors:getConversationView().renderErrors||0})
|
|
2151
|
+
if(!history.renderError)scheduleHistoryCacheSave()
|
|
2152
|
+
} catch(error) { failLoad(error,true) }
|
|
2097
2153
|
}
|
|
2098
2154
|
|
|
2099
2155
|
|
|
2100
2156
|
const INTERESTING_EVENTS = new Set([
|
|
2157
|
+
'turn/start', 'turn/end',
|
|
2101
2158
|
'user/message', 'assistant/message', 'tool/call', 'tool/result',
|
|
2102
2159
|
'agent/status', 'checkpoint/created', 'compaction/complete', 'compaction/summary',
|
|
2103
2160
|
'goal/created', 'goal/updated', 'goal/completed', 'goal/cleared',
|
|
@@ -2224,6 +2281,8 @@ function eventHtml(entry) {
|
|
|
2224
2281
|
const ev = entry.event || {}
|
|
2225
2282
|
const data = ev.data || {}
|
|
2226
2283
|
const type = ev.type || 'event'
|
|
2284
|
+
if (entry.view?.turnResult) return window.DshTurnResults.html(entry.view.turnResult)
|
|
2285
|
+
if (type === 'turn/start' || type === 'turn/end') return ''
|
|
2227
2286
|
if (entry.view?.activityGroup) return activityGroupHtml(entry.view.activityGroup)
|
|
2228
2287
|
if (!shouldShowEvent(type, ev)) return ''
|
|
2229
2288
|
if (window.DshActivity && (type==='tool/call'||type==='tool/result')) return window.DshActivity.toolEvent(entry)
|
|
@@ -2255,6 +2314,34 @@ function eventHtml(entry) {
|
|
|
2255
2314
|
if (type === 'question/asked') return `<div class="ds-tool">❓ ${esc(data.question || '')}</div>`
|
|
2256
2315
|
return `<div class="ds-tool">${esc(type)}</div>`
|
|
2257
2316
|
}
|
|
2317
|
+
function canForkTurnResult() {
|
|
2318
|
+
const session = state.byId.get(state.current)
|
|
2319
|
+
return !!session && session.origin !== 'subagent' && session.formatStatus !== 'migration-required' && activeGatewayCapability('operations') === true
|
|
2320
|
+
}
|
|
2321
|
+
function bindTurnResultActions() {
|
|
2322
|
+
window.DshTurnResults.bind($('history'), {
|
|
2323
|
+
capture: () => {
|
|
2324
|
+
const connection = captureConnection(), sessionId = state.current, history = state.history
|
|
2325
|
+
return { sessionId, entries: history.visible, key: JSON.stringify([connection.server, connection.token]), canFork: canForkTurnResult(),
|
|
2326
|
+
valid: () => connection.valid() && state.current === sessionId && state.history === history }
|
|
2327
|
+
},
|
|
2328
|
+
copy: copyText,
|
|
2329
|
+
fork: payload => rpc('session.fork', payload),
|
|
2330
|
+
open: async (id, context) => {
|
|
2331
|
+
const parent = state.byId.get(context.sessionId)
|
|
2332
|
+
try { await refreshSessions() } catch {} // A successful fork remains usable if the roster refresh fails.
|
|
2333
|
+
if (!context.valid()) return
|
|
2334
|
+
if (!state.byId.has(id)) {
|
|
2335
|
+
const branch = { ...parent, sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
|
|
2336
|
+
state.byId.set(id, branch)
|
|
2337
|
+
state.sessions.unshift(branch)
|
|
2338
|
+
renderSessions()
|
|
2339
|
+
}
|
|
2340
|
+
await openSession(id)
|
|
2341
|
+
}
|
|
2342
|
+
})
|
|
2343
|
+
}
|
|
2344
|
+
|
|
2258
2345
|
function renderHistory(reset=false, mode='auto') {
|
|
2259
2346
|
let prepared=window.DshActivity?.prepare(state.history.visible)||state.history.visible
|
|
2260
2347
|
if(weakStreamTrim())prepared=prepared.filter(entry=>entry.event?.type!=='tool/call'||entry.view?.toolActivity)
|
|
@@ -2264,6 +2351,10 @@ function renderHistory(reset=false, mode='auto') {
|
|
|
2264
2351
|
const groups = prepared.filter(entry => entry.view?.activityGroup)
|
|
2265
2352
|
const activeGroup = groups.at(-1)
|
|
2266
2353
|
if (activeGroup) activeGroup.view.activityGroup.running = sessionRunning
|
|
2354
|
+
if (window.DshTurnResults) {
|
|
2355
|
+
prepared = window.DshTurnResults.decorate(prepared, state.history.visible, { sessionId: state.current, canFork: canForkTurnResult() })
|
|
2356
|
+
bindTurnResultActions()
|
|
2357
|
+
}
|
|
2267
2358
|
getConversationView().set(prepared,{reset,follow:mode==='bottom',live:partialReasoningHtml(),hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('ds.historyEmpty')})
|
|
2268
2359
|
window.DshImagePreview?.hydrate?.($('history'))
|
|
2269
2360
|
}
|
|
@@ -3515,15 +3606,15 @@ async function probeOverviewLinks(signal) {
|
|
|
3515
3606
|
let timer
|
|
3516
3607
|
const controller=new AbortController(),cancel=()=>controller.abort()
|
|
3517
3608
|
signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)controller.abort()
|
|
3518
|
-
timer=setTimeout(cancel,
|
|
3519
|
-
const healthRequest=fetch(base+'/health?probe=
|
|
3609
|
+
timer=setTimeout(cancel,6500)
|
|
3610
|
+
const healthRequest=fetch(base+'/health?probe=fresh&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
|
|
3520
3611
|
if(!response.ok)throw Error('health')
|
|
3521
3612
|
const health=await response.json();if(health?.ok!==true)throw Error('health')
|
|
3522
3613
|
return health
|
|
3523
3614
|
}).catch(()=>null).finally(()=>{clearTimeout(timer);signal.removeEventListener('abort',cancel)})
|
|
3524
3615
|
const [health,host]=await Promise.all([healthRequest,refreshHostDescriptionDesktop()])
|
|
3525
3616
|
if(!connection.valid()||signal.aborted)throw Error('stale check')
|
|
3526
|
-
if(health){
|
|
3617
|
+
if(health){state.gatewayHealth[base]=health}
|
|
3527
3618
|
else delete state.gatewayHealth[base]
|
|
3528
3619
|
return {gateway:!!health}
|
|
3529
3620
|
}
|
|
@@ -3646,7 +3737,19 @@ function setMobileSidebar(open) {
|
|
|
3646
3737
|
function openDesktopPlugins(route = 'manage') {
|
|
3647
3738
|
const connection=captureConnection()
|
|
3648
3739
|
if(!connection.token){$('desktop-plugin-page').textContent=t('ds.toastAuth');return}
|
|
3649
|
-
window.DshExtensions.mount({connection,
|
|
3740
|
+
window.DshExtensions.mount({connection,getWorkspaces: () => state.workspaces || [],
|
|
3741
|
+
getWorkspaceId: () => (state.workspaces || []).find(w => (w.sessionIds || []).includes(state.current))?.workspaceId || '',
|
|
3742
|
+
openTeamCaptain: async id => { if (!connection.valid()) return; await openSession(id) },
|
|
3743
|
+
openTeamMember: async (id, parentId) => {
|
|
3744
|
+
const selected = state.current
|
|
3745
|
+
const catalog = await loadSessionSubagents(parentId)
|
|
3746
|
+
if (!connection.valid() || state.view !== 'view-plugins' || state.current !== selected) return
|
|
3747
|
+
const entry = catalog?.entries?.find(row => row.id === id)
|
|
3748
|
+
if (!entry || entry.kind === 'diagnostic') throw Error('unavailable')
|
|
3749
|
+
rememberSubagent(entry, parentId)
|
|
3750
|
+
await openSession(id)
|
|
3751
|
+
},
|
|
3752
|
+
back:()=>showView('view-settings'),getSession:()=>state.byId.get(state.current),getTitle:()=>titleOf(state.byId.get(state.current)),openContext:()=>void openInsights('context',true),scrollTop:()=>{$('view-plugins').scrollTop=0},url:path=>connection.server+path,headers:{authorization:'Bearer '+connection.token,'x-dsh-remote-client':'web',...clientIdHeaders()},valid:connection.valid},$('desktop-plugin-page'),route)
|
|
3650
3753
|
}
|
|
3651
3754
|
|
|
3652
3755
|
function showView(id) {
|
|
@@ -4088,3 +4191,6 @@ function mountWorkflowDesktop() {
|
|
|
4088
4191
|
recover:(row,receipt)=>{const value=receipt.result?.result?.value;if(row.method==='session.create'&&value?.sessionId)void openSession(value.sessionId);if(row.sessionId===state.current)void resyncCurrentSession()},
|
|
4089
4192
|
})
|
|
4090
4193
|
}
|
|
4194
|
+
|
|
4195
|
+
// Operation logs stay on this device; users can copy or export them.
|
|
4196
|
+
globalThis.DshDiagnostics?.configure({surface:"desktop",copy:copyText,snapshot:()=>({sessionId:state.current,server:state.server,loading:!!state.history.loading,loaded:!!state.history.loaded,count:state.history.visible.length,...globalThis.DshDiagnostics.nativeSnapshot()})})
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/* Device-local operation evidence. No message bodies, uploads or dependencies. */
|
|
2
|
+
'use strict'
|
|
3
|
+
function createDiagnosticSchema() {
|
|
4
|
+
const MAX_EVENTS=160,MAX_BYTES=48000
|
|
5
|
+
const kinds=new Set(['rpc','history.load','history.cache','history.render','history.row','session.open','session.back','stream.state','stream.retry','poll.state','client.lifecycle','client.error','feedback.submit'])
|
|
6
|
+
const enums={phase:['start','response','prepared','rendered','complete','failed','navigate','cleanup','hit','miss','retry'],channel:['mux','host'],status:['open','closed','connecting','poll','ws','visible','hidden','online','offline','running','stopped','starting','disabled','start-failed','timeout','error','unknown','granted','denied','default'],category:['authentication','timeout','network','render','syntax','upstream','unknown'],errorName:['Error','TypeError','RangeError','SyntaxError','ReferenceError','AbortError','TimeoutError','NetworkError']}
|
|
7
|
+
enums.serviceState=['starting','running','stopped','disabled','start-failed','system-timeout','auth-expired']
|
|
8
|
+
const numbers=['durationMs','httpStatus','closeCode','attempt','delayMs','count','rawCount','renderedCount','renderErrors','lastSuccessAt','intervalMin','apiLevel']
|
|
9
|
+
const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled']
|
|
10
|
+
const methods=new Set(['session.list','session.history','session.create','session.prompt','session.fork','session.cancel','session.rename','session.selectModel','session.updateQueue','session.getModels','session.getQueue','session.getCompactionStatus','workspace.list','workspace.create','workspace.archiveSession','host.describe','subagent.list','subagent.interrupt','goal.edit','goal.pause','goal.resume','goal.complete','goal.clear'])
|
|
11
|
+
for(const method of ['session.models','llm.discoverModels','llm.providers','credentials.describe','credentials.set','credentials.unset','settings.describe','settings.mutate','settings.openDocument'])methods.add(method)
|
|
12
|
+
const hex=(v,n)=>typeof v==='string'&&new RegExp('^[a-f0-9]{'+n+'}$').test(v)?v:undefined
|
|
13
|
+
const version=v=>typeof v==='string'&&/^\d+\.\d+\.\d+(?:[.-][a-zA-Z0-9.-]{1,30})?$/.test(v)?v:'unknown'
|
|
14
|
+
function facts(input={}) {
|
|
15
|
+
const out={}
|
|
16
|
+
for(const [key,values]of Object.entries(enums))if(values.includes(input[key]))out[key]=input[key]
|
|
17
|
+
for(const key of numbers)if(typeof input[key]==='number'&&Number.isFinite(input[key])&&input[key]>=0)out[key]=Math.min(input[key],Number.MAX_SAFE_INTEGER)
|
|
18
|
+
for(const key of booleans)if(typeof input[key]==='boolean')out[key]=input[key]
|
|
19
|
+
if(methods.has(input.method))out.method=input.method
|
|
20
|
+
for(const key of ['sessionRef','serverRef'])if(hex(input[key],16))out[key]=input[key]
|
|
21
|
+
if(hex(input.traceId,24))out.traceId=input.traceId
|
|
22
|
+
if(Array.isArray(input.frames))out.frames=input.frames.slice(0,3).filter(f=>['app.js','desktop.js','history.js','activity.js','turn-results.js','network.js','operations.js','diagnostics.js'].includes(f?.file)&&Number.isSafeInteger(f.line)&&f.line>0&&Number.isSafeInteger(f.column)&&f.column>0).map(f=>({file:f.file,line:f.line,column:f.column}))
|
|
23
|
+
return out
|
|
24
|
+
}
|
|
25
|
+
function sanitizeReport(input) {
|
|
26
|
+
if(!input||input.schema!==1||!Array.isArray(input.events))return null
|
|
27
|
+
const report={schema:1,reportId:hex(input.reportId,24)||'000000000000000000000000',capturedAt:typeof input.capturedAt==='number'&&Number.isFinite(input.capturedAt)?input.capturedAt:0,
|
|
28
|
+
client:{version:version(input.client?.version),buildId:hex(input.client?.buildId,64)||'unknown',surface:['mobile','desktop'].includes(input.client?.surface)?input.client.surface:'mobile'},
|
|
29
|
+
snapshot:facts(input.snapshot),events:[]}
|
|
30
|
+
for(const item of input.events.slice(-MAX_EVENTS))if(item&&kinds.has(item.kind)&&typeof item.at==='number'&&Number.isFinite(item.at))report.events.push({at:item.at,kind:item.kind,...facts(item)})
|
|
31
|
+
while(JSON.stringify(report).length>MAX_BYTES&&report.events.length)report.events.shift()
|
|
32
|
+
return report
|
|
33
|
+
}
|
|
34
|
+
return {MAX_EVENTS,MAX_BYTES,kinds,facts,sanitizeReport}
|
|
35
|
+
}
|
|
36
|
+
;(function(root){
|
|
37
|
+
const schema=createDiagnosticSchema()
|
|
38
|
+
function createDiagnostics(env) {
|
|
39
|
+
const KEY='dshRemoteDiagnosticsV1',SALT_KEY=KEY+'Salt',MAX_AGE=86400000
|
|
40
|
+
let rows=[],timer,config={},metadata={},sequence=0,sheet,exportTimer
|
|
41
|
+
const random=()=>{const bytes=new Uint8Array(12);env.crypto?.getRandomValues?.(bytes);return [...bytes].map(n=>n.toString(16).padStart(2,'0')).join('')}
|
|
42
|
+
let salt=random(),run=random()
|
|
43
|
+
try{salt=env.localStorage.getItem(SALT_KEY)||salt;env.localStorage.setItem(SALT_KEY,salt);const saved=JSON.parse(env.localStorage.getItem(KEY)||'null');rows=schema.sanitizeReport(saved)?.events||[]}catch{}
|
|
44
|
+
const now=()=>Date.now()
|
|
45
|
+
const pseudonym=value=>{if(!value||!env.SHA256)return undefined;try{return new env.SHA256().update(new TextEncoder().encode(salt+'\0'+value)).hex().slice(0,16)}catch{return undefined}}
|
|
46
|
+
const trim=()=>{rows=rows.filter(row=>row.at>now()-MAX_AGE&&row.at<=now()+60000).slice(-schema.MAX_EVENTS);while(JSON.stringify(rows).length>schema.MAX_BYTES-3000)rows.shift()}
|
|
47
|
+
function snapshot(){let value={};try{value=config.snapshot?.()||{}}catch{};return schema.facts({...value,sessionRef:pseudonym(value.sessionId),serverRef:pseudonym(value.server||env.location?.origin),online:env.navigator?.onLine!==false})}
|
|
48
|
+
function report(){trim();return schema.sanitizeReport({schema:1,reportId:random(),capturedAt:now(),client:{...metadata,surface:config.surface||'mobile'},snapshot:snapshot(),events:rows})}
|
|
49
|
+
function flush(){if(timer)env.clearTimeout?.(timer);timer=null;try{env.localStorage.setItem(KEY,JSON.stringify(report()))}catch{}}
|
|
50
|
+
function record(kind,fields={}) {
|
|
51
|
+
if(!schema.kinds.has(kind))return
|
|
52
|
+
const row={at:now(),kind,...schema.facts({...fields,sessionRef:fields.sessionRef||pseudonym(fields.sessionId),serverRef:fields.serverRef||pseudonym(fields.server||env.location?.origin)})};rows.push(row);trim()
|
|
53
|
+
if(fields.phase==='failed'||kind==='client.error'||fields.phase==='start'&&['session.open','session.back','history.load','history.render','history.cache'].includes(kind))flush()
|
|
54
|
+
else if(!timer)timer=env.setTimeout?.(flush,500)
|
|
55
|
+
return row
|
|
56
|
+
}
|
|
57
|
+
function errorFacts(error){
|
|
58
|
+
const message=String(error?.message||''),category=/auth|ticket|401|403/i.test(message)?'authentication':/timeout|abort/i.test(message+' '+error?.name)?'timeout':/network|fetch|socket/i.test(message)?'network':error?.name==='SyntaxError'?'syntax':'unknown',frames=[]
|
|
59
|
+
for(const line of String(error?.stack||'').split('\n').slice(1,8)){const match=line.match(/(?:[/\\])(app|desktop|history|activity|turn-results|network|operations|diagnostics)\.js(?:\?[^\s:]*)?:(\d+):(\d+)\)?$/);if(match)frames.push({file:match[1]+'.js',line:Number(match[2]),column:Number(match[3])})}
|
|
60
|
+
return schema.facts({category,errorName:error?.name,frames,...(/^HTTP \d{3}$/.test(message)?{httpStatus:Number(message.slice(5))}:{})})
|
|
61
|
+
}
|
|
62
|
+
function start(kind,fields={}){const begun=now(),traceId=run.slice(0,12)+(++sequence).toString(16).padStart(12,'0');record(kind,{...fields,phase:'start',traceId});return {traceId,end:value=>record(kind,{...fields,...value,traceId,durationMs:now()-begun}),fail:error=>record(kind,{...fields,...errorFacts(error),phase:'failed',traceId,durationMs:now()-begun})}}
|
|
63
|
+
function nativeSnapshot(){try{const value=JSON.parse(env.NativeBackground?.getBackgroundConfig?.()||'{}');return schema.facts({...value,httpStatus:value.lastHttpStatus})}catch{return {}}}
|
|
64
|
+
function configure(value){config=value;record('client.lifecycle',{status:env.document?.visibilityState==='hidden'?'hidden':'visible',...nativeSnapshot()});mount()}
|
|
65
|
+
function clear(){rows=[];flush();refreshPreview()}
|
|
66
|
+
function text(){return JSON.stringify(report(),null,2)}
|
|
67
|
+
const label=(zh,en)=>env.I18N?.lang==='en'?en:zh
|
|
68
|
+
const $=id=>env.document?.getElementById(id)
|
|
69
|
+
function refreshPreview(){const node=$('fb-client-log-preview');if(node)node.textContent=text()}
|
|
70
|
+
function exportStatus(attempt=0){
|
|
71
|
+
const status=$('fb-client-log-status');let phase='error'
|
|
72
|
+
try{phase=env.NativeFile.getDiagnosticExportStatus()}catch{}
|
|
73
|
+
if(status)status.textContent=phase==='saved'?label('日志已保存','Report saved'):phase==='cancelled'?label('已取消保存','Save cancelled'):phase==='picking'?label('请在系统文件选择器中保存日志','Save the report in the system file picker'):label('导出失败,请复制日志。','Export failed. Copy the report instead.')
|
|
74
|
+
if(phase==='picking'&&attempt<120)exportTimer=env.setTimeout(()=>exportStatus(attempt+1),1000)
|
|
75
|
+
}
|
|
76
|
+
function download(){try{
|
|
77
|
+
if(env.NativeFile?.exportDiagnostics){if(!env.NativeFile.exportDiagnostics(text()))throw Error('export unavailable');if(exportTimer)env.clearTimeout(exportTimer);exportStatus();return}
|
|
78
|
+
if(env.NativeBackground)throw Error('native export unavailable')
|
|
79
|
+
const blob=new env.Blob([text()],{type:'application/json'}),url=env.URL.createObjectURL(blob),a=env.document.createElement('a');a.href=url;a.download='dsh-diagnostics-'+now()+'.json';env.document.body.append(a);a.click();a.remove();env.setTimeout(()=>env.URL.revokeObjectURL(url),1000)
|
|
80
|
+
}catch{const status=$('fb-client-log-status');if(status)status.textContent=label('导出失败,请复制日志。','Export failed. Copy the report instead.')}}
|
|
81
|
+
function show(){if(!sheet)return;const status=$('fb-client-log-status');if(status)status.textContent='';refreshPreview();$('fb-client-log-details').open=true;if(!sheet.open)sheet.showModal()}
|
|
82
|
+
function mount(){
|
|
83
|
+
const details=$('fb-client-log-details');if(!details||details.dataset.bound)return;details.dataset.bound='1'
|
|
84
|
+
const panel=details.closest('.client-diagnostics'),entry=env.document.createElement('button');entry.type='button';entry.className='workflow-button';entry.dataset.logLabel='entry';panel.parentNode.insertBefore(entry,panel);entry.addEventListener('click',show)
|
|
85
|
+
sheet=env.document.createElement('dialog');sheet.className='client-log-dialog';sheet.setAttribute('aria-labelledby','client-log-title')
|
|
86
|
+
const head=env.document.createElement('div');head.className='client-log-head';const title=env.document.createElement('h2');title.id='client-log-title';title.dataset.logLabel='title';const close=env.document.createElement('button');close.type='button';close.dataset.logLabel='close';close.addEventListener('click',()=>sheet.close());head.append(title,close);sheet.append(head,panel);env.document.body.append(sheet)
|
|
87
|
+
const labels={entry:['查看本地操作日志','View local operation logs'],title:['本地操作日志','Local operation logs'],close:['关闭','Close'],privacy:['操作日志仅保存在此设备,记录操作阶段、耗时、错误位置与连接状态。可复制或导出后自行反馈。','Operation logs stay on this device and include stages, durations, error locations and connection status. Copy or export them to share feedback yourself.'],details:['查看详细记录','View detailed records'],refresh:['刷新预览','Refresh preview'],copy:['复制日志','Copy report'],export:['导出日志','Export report'],clear:['清除日志','Clear report']}
|
|
88
|
+
const translate=()=>{for(const node of env.document.querySelectorAll('[data-log-label]')){const pair=labels[node.dataset.logLabel];if(pair)node.textContent=label(...pair)}}
|
|
89
|
+
translate();if(env.MutationObserver)new env.MutationObserver(translate).observe(env.document.documentElement,{attributes:true,attributeFilter:['lang']})
|
|
90
|
+
details.addEventListener('toggle',()=>{if(details.open)refreshPreview()})
|
|
91
|
+
$('fb-log-preview')?.addEventListener('click',refreshPreview)
|
|
92
|
+
$('fb-log-copy')?.addEventListener('click',async()=>{const status=$('fb-client-log-status');let ok=false;try{ok=!!await config.copy?.(text())}catch{};if(status)status.textContent=ok?label('已复制脱敏日志','Report copied'):label('复制失败,请导出日志。','Copy failed. Export the report instead.')})
|
|
93
|
+
$('fb-log-export')?.addEventListener('click',download)
|
|
94
|
+
$('fb-log-clear')?.addEventListener('click',clear)
|
|
95
|
+
}
|
|
96
|
+
env.addEventListener?.('error',event=>record('client.error',{...errorFacts(event.error),phase:'failed'}))
|
|
97
|
+
env.addEventListener?.('unhandledrejection',event=>record('client.error',{...errorFacts(event.reason),phase:'failed'}))
|
|
98
|
+
for(const status of ['online','offline'])env.addEventListener?.(status,()=>record('client.lifecycle',{status,online:status==='online'}))
|
|
99
|
+
env.document?.addEventListener('visibilitychange',()=>{record('client.lifecycle',{status:env.document.visibilityState==='visible'?'visible':'hidden',...nativeSnapshot()});flush()})
|
|
100
|
+
env.addEventListener?.('pagehide',flush)
|
|
101
|
+
function build(value){metadata={version:value?.version,buildId:value?.buildId}}
|
|
102
|
+
return {record,start,errorFacts,report,text,flush,clear,configure,show,download,build,nativeSnapshot}
|
|
103
|
+
}
|
|
104
|
+
if(typeof module!=='undefined'&&module.exports)module.exports={createDiagnostics,createDiagnosticSchema}
|
|
105
|
+
else {
|
|
106
|
+
root.DshDiagnostics=createDiagnostics(root)
|
|
107
|
+
try{const url=new URL('build.json',root.document.currentScript.src);void root.fetch(url,{cache:'no-store',signal:AbortSignal.timeout(5000)}).then(r=>r.ok?r.json():{}).then(value=>root.DshDiagnostics.build(value)).catch(()=>{})}catch{}
|
|
108
|
+
}
|
|
109
|
+
})(typeof window==='undefined'?globalThis:window)
|