dsh-remote-plugin 0.9.0 → 0.9.1
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 +58 -8
- package/package.json +1 -1
- package/public/activity.js +45 -7
- package/public/admin.html +31 -31
- package/public/announcements.json +36 -0
- package/public/app.js +370 -62
- package/public/build.json +2 -2
- package/public/desktop/desktop.html +82 -80
- package/public/desktop/desktop.js +95 -6
- package/public/e2ee-config.js +5 -0
- package/public/e2ee-transport.js +23 -4
- package/public/history.js +114 -17
- package/public/index.html +88 -86
- package/public/plan-review.js +23 -2
- package/public/plugin.html +27 -27
- package/public/relay-autopair.js +5 -0
- package/public/relay-devices.js +7 -3
- package/public/relay-settings.js +32 -12
- package/public/session-cache.js +85 -0
- package/public/skins/blue-fish/preview.html +3 -3
- package/public/skins/bocchi/preview.html +5 -5
- package/public/skins/kita/preview.html +6 -6
- package/public/skins/miku/preview.html +5 -5
- package/public/skins/nijika/preview.html +6 -6
- package/public/skins/penguin/preview.html +3 -3
- package/public/skins/ryo/preview.html +6 -6
- package/public/update.json +8 -8
- package/public/version.json +1 -1
- package/public/workflow.css +3 -3
package/public/app.js
CHANGED
|
@@ -34,10 +34,40 @@ const CACHE = {
|
|
|
34
34
|
get history() { return connectionCacheKey('history') }
|
|
35
35
|
}
|
|
36
36
|
function connectionCacheKey(kind, server=state.server, token=state.token) {
|
|
37
|
+
const peer = verifiedCachePeer(server, token)
|
|
38
|
+
return cacheKeyFor(kind, peer ? ['relay', peer, token] : [server || location.origin, token])
|
|
39
|
+
}
|
|
40
|
+
function cacheKeyFor(kind, identity) {
|
|
37
41
|
const hash = new SHA256()
|
|
38
|
-
hash.update(new TextEncoder().encode(JSON.stringify(
|
|
42
|
+
hash.update(new TextEncoder().encode(JSON.stringify(identity)))
|
|
39
43
|
return kind + 'CacheV2:' + hash.hex()
|
|
40
44
|
}
|
|
45
|
+
function verifiedCachePeer(server, token) {
|
|
46
|
+
if (globalThis.DSH_REMOTE_E2EE_DISABLED === true) return ''
|
|
47
|
+
const entry = state.servers?.find(item => item.url === server && serverToken(item) === token && item.cacheRelayPin)
|
|
48
|
+
if (!entry) return ''
|
|
49
|
+
try {
|
|
50
|
+
const pair = JSON.parse(window.NativeE2ee.info(entry.cacheRelayOrigin))
|
|
51
|
+
if (pair.configured && pair.encrypted && !pair.error && pair.fingerprint === entry.cacheRelayPin) return entry.cacheRelayPin
|
|
52
|
+
} catch {}
|
|
53
|
+
return ''
|
|
54
|
+
}
|
|
55
|
+
function connectionCacheReadKeys(kind, server=state.server, token=state.token) {
|
|
56
|
+
const primary = connectionCacheKey(kind, server, token)
|
|
57
|
+
const peer = verifiedCachePeer(server, token)
|
|
58
|
+
if (!peer) return [primary]
|
|
59
|
+
const addresses = [server, ...state.servers.filter(item => serverToken(item) === token &&
|
|
60
|
+
verifiedCachePeer(item.url, token) === peer).map(item => item.url)]
|
|
61
|
+
return [primary, ...new Set(addresses.map(url => cacheKeyFor(kind, [url || location.origin, token])))]
|
|
62
|
+
}
|
|
63
|
+
function readCachedSessions() {
|
|
64
|
+
const keys = typeof connectionCacheReadKeys === 'function' ? connectionCacheReadKeys('sessions') : [CACHE.sessions]
|
|
65
|
+
for (const key of keys) {
|
|
66
|
+
const items = globalThis.DshSessionCache?.readKey ? globalThis.DshSessionCache.readKey(key) : cacheRead(key)
|
|
67
|
+
if (Array.isArray(items)) return items
|
|
68
|
+
}
|
|
69
|
+
return []
|
|
70
|
+
}
|
|
41
71
|
function cacheRead(key, d = null) {
|
|
42
72
|
try { return JSON.parse(LS.get(key, '')) || d } catch { return d }
|
|
43
73
|
}
|
|
@@ -517,12 +547,36 @@ function fmtFullTime(ts) {
|
|
|
517
547
|
|
|
518
548
|
/* ---------------- API ---------------- */
|
|
519
549
|
function saveAutoPairedRelay(origin, connection) {
|
|
520
|
-
if (!connection.valid()) return
|
|
550
|
+
if (globalThis.DSH_REMOTE_E2EE_DISABLED === true || !connection.valid()) return
|
|
521
551
|
const token=connection.headers.authorization.slice(7)
|
|
522
|
-
|
|
523
|
-
|
|
552
|
+
let entry = state.servers.find(s=>s.url===origin&&serverToken(s)===token&&s.group===state.activeGroup)
|
|
553
|
+
const added = !entry
|
|
554
|
+
if (!entry) {
|
|
555
|
+
entry = {id:newServerId(),url:origin,note:I18N.lang==='en'?'Cloud relay':'公网中转',group:state.activeGroup,token}
|
|
556
|
+
state.servers.push(entry)
|
|
557
|
+
}
|
|
558
|
+
// A verified public address belongs to the same host group; keep one credential for the group.
|
|
559
|
+
syncGroupToken(entry.group || state.activeGroup, token)
|
|
560
|
+
// The pairing flow has already authenticated both addresses and checked the public certificate.
|
|
561
|
+
let linked = false
|
|
562
|
+
try {
|
|
563
|
+
const pair = JSON.parse(window.NativeE2ee.info(origin))
|
|
564
|
+
const lan = connection.url('/relay').slice(0, -'/relay'.length)
|
|
565
|
+
if (pair.configured && pair.encrypted && !pair.error && /^[a-f0-9]{64}$/.test(pair.fingerprint)) {
|
|
566
|
+
for (const address of state.servers) {
|
|
567
|
+
if ([lan, origin].includes(address.url) && serverToken(address) === token &&
|
|
568
|
+
(address.cacheRelayPin !== pair.fingerprint || address.cacheRelayOrigin !== origin)) {
|
|
569
|
+
address.cacheRelayOrigin = origin
|
|
570
|
+
address.cacheRelayPin = pair.fingerprint
|
|
571
|
+
linked = true
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
} catch {}
|
|
576
|
+
if (!added && !linked) return
|
|
524
577
|
saveServers();renderServers();syncBgConfig()
|
|
525
|
-
|
|
578
|
+
if (linked) restoreCachedSessionList()
|
|
579
|
+
if (added) toast(I18N.lang==='en'?'Public access verified. LAN remains connected.':'公网已验证,局域网连接保留。','ok')
|
|
526
580
|
}
|
|
527
581
|
let relaySetup = null
|
|
528
582
|
function relaySetupFor(connection) {
|
|
@@ -530,6 +584,7 @@ function relaySetupFor(connection) {
|
|
|
530
584
|
return ''
|
|
531
585
|
}
|
|
532
586
|
function offerLocalRelayPairing(connection=captureConnection(), force=false, activationId='') {
|
|
587
|
+
if (globalThis.DSH_REMOTE_E2EE_DISABLED === true) return
|
|
533
588
|
if (!connection.token || !connection.valid()) return
|
|
534
589
|
return window.DshRelayAutoPair?.offer({
|
|
535
590
|
connection:()=>({valid:connection.valid,url:path=>connection.server+path,headers:{authorization:'Bearer '+connection.token},setupId:relaySetupFor(connection)}),
|
|
@@ -539,6 +594,7 @@ function offerLocalRelayPairing(connection=captureConnection(), force=false, act
|
|
|
539
594
|
}
|
|
540
595
|
let relayActivationSync = null
|
|
541
596
|
function syncRelayActivation(activationId, force = false) {
|
|
597
|
+
if (globalThis.DSH_REMOTE_E2EE_DISABLED === true) return
|
|
542
598
|
if (!CAP?.isNativePlatform?.() || !/^[a-f0-9]{32}$/.test(activationId || '')) return
|
|
543
599
|
if (relayActivationSync?.id === activationId && relayActivationSync.connection.valid()) return relayActivationSync.task
|
|
544
600
|
const connection = captureConnection()
|
|
@@ -583,7 +639,7 @@ async function getWsTicket() {
|
|
|
583
639
|
const data = await (globalThis.DshNetwork?.readWithDeadline
|
|
584
640
|
? globalThis.DshNetwork.readWithDeadline(read,8000)
|
|
585
641
|
: read(AbortSignal.timeout(8000)))
|
|
586
|
-
if (!connection.valid()) throw new Error('stale ws ticket')
|
|
642
|
+
if (wsTicketPromise !== job || !connection.valid()) throw new Error('stale ws ticket')
|
|
587
643
|
if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
|
|
588
644
|
state.wsTicket = { token, server, value: data.ticket, expiresAt: Number(data.expiresAt) }
|
|
589
645
|
return data.ticket
|
|
@@ -805,6 +861,24 @@ function serverKey(server) {
|
|
|
805
861
|
return serverIdentity(server?.url ?? server, server?.token)
|
|
806
862
|
}
|
|
807
863
|
function serverToken(server) { return normalizedServerToken(server?.token) }
|
|
864
|
+
function groupToken(group = state.activeGroup) {
|
|
865
|
+
const tokens = [...new Set(groupServers(group).map(serverToken).filter(Boolean))]
|
|
866
|
+
return tokens.length === 1 ? tokens[0] : ''
|
|
867
|
+
}
|
|
868
|
+
function syncGroupToken(group, token) {
|
|
869
|
+
const value = normalizedServerToken(token)
|
|
870
|
+
if (!group || !value) return 0
|
|
871
|
+
let changed = 0
|
|
872
|
+
for (const server of groupServers(group)) {
|
|
873
|
+
if (serverToken(server) === value) continue
|
|
874
|
+
server.token = value
|
|
875
|
+
// A pairing/PIN link belongs to the old credential and must not survive a token change.
|
|
876
|
+
delete server.cacheRelayPin
|
|
877
|
+
delete server.cacheRelayOrigin
|
|
878
|
+
changed++
|
|
879
|
+
}
|
|
880
|
+
return changed
|
|
881
|
+
}
|
|
808
882
|
function currentServerEntry() {
|
|
809
883
|
return state.servers.find(s => s.url === state.server && serverToken(s) === state.token)
|
|
810
884
|
|| state.servers.find(s => s.url === state.server)
|
|
@@ -814,7 +888,8 @@ function setCurrentAccessToken(value) {
|
|
|
814
888
|
const token = normalizedServerToken(value)
|
|
815
889
|
if (!token) return false
|
|
816
890
|
const current = currentServerEntry()
|
|
817
|
-
|
|
891
|
+
// A group is one host/credential: changing the token must not leave siblings on the old one.
|
|
892
|
+
syncGroupToken(current?.group || state.activeGroup, token)
|
|
818
893
|
state.token = token
|
|
819
894
|
LS.set('token', token)
|
|
820
895
|
saveServers()
|
|
@@ -857,7 +932,8 @@ function loadServers() {
|
|
|
857
932
|
}
|
|
858
933
|
const legacyToken = normalizedServerToken(state.token || LS.get('token', ''))
|
|
859
934
|
state.servers = data.servers.filter(s => s && typeof s.url === 'string')
|
|
860
|
-
.map(s => ({ id: s.id || newServerId(), url: s.url.replace(/\/+$/, ''), note: s.note || '', group: s.group || '默认', token: s.token == null ? legacyToken : normalizedServerToken(s.token)
|
|
935
|
+
.map(s => ({ id: s.id || newServerId(), url: s.url.replace(/\/+$/, ''), note: s.note || '', group: s.group || '默认', token: s.token == null ? legacyToken : normalizedServerToken(s.token),
|
|
936
|
+
...(typeof s.cacheRelayOrigin === 'string' && /^[a-f0-9]{64}$/.test(s.cacheRelayPin || '') ? { cacheRelayOrigin: s.cacheRelayOrigin, cacheRelayPin: s.cacheRelayPin } : {}) }))
|
|
861
937
|
state.groups = Array.isArray(data.groups) && data.groups.length ? data.groups : ['默认']
|
|
862
938
|
state.activeGroup = state.groups.includes(data.activeGroup) ? data.activeGroup : '默认'
|
|
863
939
|
state.autoSelect = data.autoSelect || {}
|
|
@@ -908,12 +984,13 @@ function pingServer(base, token) {
|
|
|
908
984
|
}
|
|
909
985
|
|
|
910
986
|
function activeGatewayCapability(name) {
|
|
911
|
-
const capabilities = activeGatewayHealth()?.capabilities
|
|
987
|
+
const capabilities = activeGatewayHealth({ allowStale: true })?.capabilities
|
|
912
988
|
if (!capabilities || !Object.prototype.hasOwnProperty.call(capabilities, name)) return null
|
|
913
989
|
return Number(capabilities[name]) > 0
|
|
914
990
|
}
|
|
915
991
|
|
|
916
|
-
function activeGatewayHealth() {
|
|
992
|
+
function activeGatewayHealth({ allowStale = false } = {}) {
|
|
993
|
+
if (!allowStale && currentConnectionHealth() === null) return null
|
|
917
994
|
const key = String(state.server || location.origin || '').replace(/\/+$/, '')
|
|
918
995
|
return state.gatewayHealth[key] || null
|
|
919
996
|
}
|
|
@@ -938,17 +1015,25 @@ async function refreshConnectionHealth() {
|
|
|
938
1015
|
const base = String(connection.server || location.origin).replace(/\/+$/, '')
|
|
939
1016
|
const probe = { connection, health: current?.health, task: null }
|
|
940
1017
|
connectionHealthProbe = probe
|
|
941
|
-
|
|
942
|
-
let health = null
|
|
1018
|
+
const read = async (url, signal) => {
|
|
943
1019
|
try {
|
|
944
|
-
const response = await fetch(
|
|
1020
|
+
const response = await fetch(url, { cache: 'no-store', signal })
|
|
945
1021
|
const value = response.ok ? await response.json() : null
|
|
946
|
-
|
|
1022
|
+
return value?.ok === true ? value : null
|
|
947
1023
|
} catch {}
|
|
1024
|
+
return null
|
|
1025
|
+
}
|
|
1026
|
+
probe.task = (async () => {
|
|
1027
|
+
let health = await read(base + '/health?probe=fresh', AbortSignal.timeout(6500))
|
|
1028
|
+
if (!health && probe === connectionHealthProbe && connection.valid()) {
|
|
1029
|
+
// The fresh probe waits for DSH. Check gateway liveness separately if that request fails.
|
|
1030
|
+
const live = await read(base + '/health?probe=live', AbortSignal.timeout(3500))
|
|
1031
|
+
if (live?.service === 'dsh-remote') health = live
|
|
1032
|
+
}
|
|
948
1033
|
if (probe !== connectionHealthProbe || !connection.valid()) return null
|
|
949
1034
|
probe.health = health
|
|
1035
|
+
// Failed probes do not invalidate advertised capabilities such as message receipts.
|
|
950
1036
|
if (health) state.gatewayHealth[base] = health
|
|
951
|
-
else delete state.gatewayHealth[base]
|
|
952
1037
|
probe.task = null
|
|
953
1038
|
updateConn()
|
|
954
1039
|
return health
|
|
@@ -1407,9 +1492,12 @@ function renderServers() {
|
|
|
1407
1492
|
const list = groupServers(g)
|
|
1408
1493
|
const auto = state.autoSelect[g] !== false
|
|
1409
1494
|
const activeManual = state.groupActive[g] || ''
|
|
1495
|
+
const tokens = new Set(list.map(serverToken).filter(Boolean))
|
|
1496
|
+
const mixedToken = tokens.size > 1
|
|
1410
1497
|
return `<div class="srv-group" data-group="${esc(g)}">
|
|
1411
1498
|
<div class="srv-group-head">
|
|
1412
1499
|
<button class="srv-group-name" data-group-name="${esc(g)}"><span class="srv-group-label">${g === state.activeGroup ? '▾' : '▸'} ${esc(g)}</span><span class="srv-group-count">${list.length}</span></button>
|
|
1500
|
+
${mixedToken ? `<button class="srv-group-sync mini-btn" data-sync-group="${esc(g)}" title="${I18N.lang === 'en' ? 'This group has mixed tokens; use the current connection token for all addresses' : '本组地址令牌不一致,点击用当前连接令牌统一'}">${I18N.lang === 'en' ? 'Sync token' : '统一令牌'}</button>` : ''}
|
|
1413
1501
|
<button class="srv-group-speed mini-btn" data-speed-group="${esc(g)}" title="${t('groups.speedTest')}">⚡</button>
|
|
1414
1502
|
<label class="switch small" title="${t('groups.autoSelect')}">
|
|
1415
1503
|
<input type="checkbox" data-auto-group="${esc(g)}" ${auto ? 'checked' : ''}>
|
|
@@ -1448,6 +1536,20 @@ function renderServers() {
|
|
|
1448
1536
|
b.addEventListener('dblclick', () => renameGroup(b.dataset.groupName))
|
|
1449
1537
|
})
|
|
1450
1538
|
box.querySelectorAll('[data-speed-group]').forEach(b => b.addEventListener('click', () => { state.activeGroup = b.dataset.speedGroup; saveServers(); selectFastestServer({ silent: false }) }))
|
|
1539
|
+
box.querySelectorAll('[data-sync-group]').forEach(b => b.addEventListener('click', () => {
|
|
1540
|
+
const group = b.dataset.syncGroup
|
|
1541
|
+
const token = normalizedServerToken(state.token)
|
|
1542
|
+
if (!token) return toast(I18N.lang === 'en' ? 'No current token to sync.' : '当前没有可用的令牌。', 'err')
|
|
1543
|
+
const count = groupServers(group).length
|
|
1544
|
+
const message = I18N.lang === 'en'
|
|
1545
|
+
? `Use the current connection token for all ${count} addresses in group "${group}"?`
|
|
1546
|
+
: `用当前连接令牌统一组「${group}」的 ${count} 个地址?`
|
|
1547
|
+
if (!window.confirm(message)) return
|
|
1548
|
+
const changed = syncGroupToken(group, token)
|
|
1549
|
+
saveServers(); renderServers()
|
|
1550
|
+
toast(I18N.lang === 'en' ? `Token synced for ${changed} address(es).` : `已同步 ${changed} 个地址的令牌。`, 'ok')
|
|
1551
|
+
if (state.token) selectFastestServer({ silent: true })
|
|
1552
|
+
}))
|
|
1451
1553
|
box.querySelectorAll('[data-auto-group]').forEach(chk => chk.addEventListener('change', (e) => {
|
|
1452
1554
|
const g = e.target.dataset.autoGroup
|
|
1453
1555
|
state.autoSelect[g] = e.target.checked
|
|
@@ -1503,10 +1605,17 @@ async function addServer() {
|
|
|
1503
1605
|
} catch {
|
|
1504
1606
|
return toast(t('servers.badProtocol'), 'err')
|
|
1505
1607
|
}
|
|
1506
|
-
const
|
|
1608
|
+
const group = state.activeGroup
|
|
1609
|
+
const tokens = new Set(groupServers(group).map(serverToken).filter(Boolean))
|
|
1610
|
+
if (tokens.size > 1) {
|
|
1611
|
+
return toast(I18N.lang === 'en'
|
|
1612
|
+
? 'This group has mixed tokens. Unify them before adding another address.'
|
|
1613
|
+
: '本组地址令牌不一致,请先点击「统一令牌」再添加地址。', 'err')
|
|
1614
|
+
}
|
|
1615
|
+
const token = tokens.size === 1 ? [...tokens][0] : normalizedServerToken(state.token)
|
|
1507
1616
|
if (state.servers.some(s => serverIdentity(s.url, serverToken(s)) === serverIdentity(raw, token))) return toast(t('servers.duplicate'))
|
|
1508
1617
|
let note = prompt(t('servers.promptNote'), '') || ''
|
|
1509
|
-
state.servers.push({ id: newServerId(), url: raw, note: note.trim(), group
|
|
1618
|
+
state.servers.push({ id: newServerId(), url: raw, note: note.trim(), group, token })
|
|
1510
1619
|
saveServers()
|
|
1511
1620
|
if (input) input.value = ''
|
|
1512
1621
|
renderServers()
|
|
@@ -1535,10 +1644,17 @@ function editServer(id) {
|
|
|
1535
1644
|
if (group === null) return
|
|
1536
1645
|
const wasActive = state.server === s.url && state.token === serverToken(s)
|
|
1537
1646
|
const changedActiveUrl = wasActive && state.server !== raw
|
|
1647
|
+
const previousToken = serverToken(s)
|
|
1648
|
+
if (s.url !== raw || serverToken(s) !== token) {
|
|
1649
|
+
delete s.cacheRelayOrigin
|
|
1650
|
+
delete s.cacheRelayPin
|
|
1651
|
+
}
|
|
1538
1652
|
s.url = raw
|
|
1539
1653
|
s.note = note.trim()
|
|
1540
1654
|
s.group = ensureGroup(group.trim() || '默认')
|
|
1541
1655
|
s.token = token
|
|
1656
|
+
// Editing one address changes the credential for the whole group, not just this row.
|
|
1657
|
+
if (previousToken !== token) syncGroupToken(s.group, token)
|
|
1542
1658
|
if (wasActive) {
|
|
1543
1659
|
if (changedActiveUrl) resetFsForServer()
|
|
1544
1660
|
state.server = raw
|
|
@@ -1554,8 +1670,16 @@ function editServer(id) {
|
|
|
1554
1670
|
function removeServer(id) {
|
|
1555
1671
|
const s = state.servers.find(x => x.id === id)
|
|
1556
1672
|
if (!s) return
|
|
1557
|
-
|
|
1558
|
-
|
|
1673
|
+
const token = serverToken(s), peer = verifiedCachePeer(s.url, token)
|
|
1674
|
+
const scopes = [cacheKeyFor('history', [s.url, token])]
|
|
1675
|
+
if (peer && !state.servers.some(other => other.id !== id && serverToken(other) === token && verifiedCachePeer(other.url, token) === peer)) {
|
|
1676
|
+
scopes.push(historyCacheScope(s.url, token))
|
|
1677
|
+
}
|
|
1678
|
+
for (const scope of scopes) {
|
|
1679
|
+
void window.DshImageCache?.clear(scope)
|
|
1680
|
+
void window.DshHistory.cacheClear(scope)
|
|
1681
|
+
clearSessionCache(scope)
|
|
1682
|
+
}
|
|
1559
1683
|
state.servers = state.servers.filter(x => x.id !== id)
|
|
1560
1684
|
const wasActive = state.server === s.url && state.token === serverToken(s)
|
|
1561
1685
|
// 清理该组手动指定
|
|
@@ -1670,6 +1794,7 @@ function closeStream(kind) {
|
|
|
1670
1794
|
const ws = streams[kind]
|
|
1671
1795
|
streams[kind] = null
|
|
1672
1796
|
state.streamsOk[kind] = false
|
|
1797
|
+
ws?._continuity?.finish(true)
|
|
1673
1798
|
try { ws?.close() } catch {}
|
|
1674
1799
|
}
|
|
1675
1800
|
|
|
@@ -1743,8 +1868,9 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1743
1868
|
const clientMark = CAP?.isNativePlatform?.() ? 'app' : 'web'
|
|
1744
1869
|
const auth = ticket ? `ticket=${encodeURIComponent(ticket)}` : `token=${encodeURIComponent(state.token)}`
|
|
1745
1870
|
const clientId = CLIENT_ID ? `&clientId=${encodeURIComponent(CLIENT_ID)}` : ''
|
|
1746
|
-
const streamUrl = `${base}/api/events.${kind}?${auth}&client=${clientMark}${clientId}`
|
|
1747
1871
|
const current = streams[kind]
|
|
1872
|
+
const streamId = kind === 'mux' && clientMark === 'app' ? current?._continuityId || continuityNonce() : ''
|
|
1873
|
+
const streamUrl = `${base}/api/events.${kind}?${auth}&client=${clientMark}${clientId}${streamId ? '&stream=' + streamId : ''}`
|
|
1748
1874
|
if (current?._streamUrl === streamUrl &&
|
|
1749
1875
|
(current.readyState === WebSocket.OPEN || current.readyState === WebSocket.CONNECTING)) return
|
|
1750
1876
|
if (current && current._streamUrl !== streamUrl) {
|
|
@@ -1758,6 +1884,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1758
1884
|
const ws = new WebSocket(streamUrl)
|
|
1759
1885
|
streams[kind] = ws
|
|
1760
1886
|
ws._streamUrl = streamUrl
|
|
1887
|
+
ws._continuityId = streamId
|
|
1761
1888
|
ws._generation = generation
|
|
1762
1889
|
ws._isRestore = !!isRestore
|
|
1763
1890
|
ws.onopen = () => {
|
|
@@ -1797,6 +1924,10 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1797
1924
|
updateConn()
|
|
1798
1925
|
try {
|
|
1799
1926
|
const full = JSON.parse(msg.data)
|
|
1927
|
+
if (full?.type === 'relay/ws-probe') {
|
|
1928
|
+
if (ws._continuity && full.nonce === ws._continuity.nonce) ws._continuity.finish(true)
|
|
1929
|
+
return
|
|
1930
|
+
}
|
|
1800
1931
|
handler(full)
|
|
1801
1932
|
} catch {}
|
|
1802
1933
|
}
|
|
@@ -1946,9 +2077,66 @@ function tryRestoreWs() {
|
|
|
1946
2077
|
if (!streams.host && !streamMeta.host.retryTimer) openStream('host', onHostFrame, false, true)
|
|
1947
2078
|
}
|
|
1948
2079
|
|
|
2080
|
+
let backgroundConnection = null
|
|
2081
|
+
function continuityNonce() {
|
|
2082
|
+
const bytes = globalThis.crypto?.getRandomValues?.(new Uint8Array(16))
|
|
2083
|
+
return bytes ? Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('') : ''
|
|
2084
|
+
}
|
|
2085
|
+
function markRealtimeBackgrounded() {
|
|
2086
|
+
if (!state.token || !CAP?.isNativePlatform?.()) return
|
|
2087
|
+
backgroundConnection = captureConnection()
|
|
2088
|
+
streams.mux?._continuity?.finish(true)
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
function verifyRetainedMux(ws, connection) {
|
|
2092
|
+
const nonce = continuityNonce()
|
|
2093
|
+
const controller = new AbortController()
|
|
2094
|
+
const finish = alive => {
|
|
2095
|
+
if (ws._continuity?.nonce !== nonce) return
|
|
2096
|
+
ws._continuity = null
|
|
2097
|
+
clearTimeout(timer)
|
|
2098
|
+
controller.abort()
|
|
2099
|
+
if (alive || !connection.valid() || streams.mux !== ws) return
|
|
2100
|
+
closeStream('mux')
|
|
2101
|
+
if (navigator.onLine) openStream('mux', onMuxFrame, true)
|
|
2102
|
+
updateConn()
|
|
2103
|
+
}
|
|
2104
|
+
const timer = setTimeout(() => finish(false), 2500)
|
|
2105
|
+
ws._continuity = { nonce, finish }
|
|
2106
|
+
const headers = { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': 'app', ...clientIdHeaders() }
|
|
2107
|
+
// A response on HTTP is insufficient: the nonce must arrive on the retained WebSocket.
|
|
2108
|
+
void fetch(apiUrl(`/api/events.poll?kind=mux&stream=${ws._continuityId}&wsProbe=${nonce}`), {
|
|
2109
|
+
headers, signal: controller.signal, cache: 'no-store'
|
|
2110
|
+
}).then(response => { if (response.status !== 204) finish(false) }, () => finish(false))
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2113
|
+
function resetRealtimeAfterBackground() {
|
|
2114
|
+
const reconnect = backgroundConnection?.valid()
|
|
2115
|
+
backgroundConnection = null
|
|
2116
|
+
if (!reconnect) return
|
|
2117
|
+
|
|
2118
|
+
// Android can suspend the relay path without delivering a WebSocket close to the WebView.
|
|
2119
|
+
wsTicketPromise = null
|
|
2120
|
+
wsTicketConnection = null
|
|
2121
|
+
connectionHealthProbe = null
|
|
2122
|
+
clearReconnect()
|
|
2123
|
+
const mux = streams.mux
|
|
2124
|
+
const retainMux = navigator.onLine && state.streamMode === 'ws' && mux?.readyState === WebSocket.OPEN &&
|
|
2125
|
+
mux._continuityId && activeGatewayCapability('streamContinuity') === true
|
|
2126
|
+
for (const kind of ['mux', 'host']) {
|
|
2127
|
+
if (kind !== 'mux' || !retainMux) closeStream(kind)
|
|
2128
|
+
streamMeta[kind].attempt = 0
|
|
2129
|
+
streamMeta[kind].failures = 0
|
|
2130
|
+
}
|
|
2131
|
+
aggregateStreamFailures()
|
|
2132
|
+
if (state.streamMode === 'poll') stopPolling()
|
|
2133
|
+
if (retainMux) verifyRetainedMux(mux, captureConnection())
|
|
2134
|
+
}
|
|
2135
|
+
|
|
1949
2136
|
/* 回前台恢复: 强制重排修复 MIUI WebView 后台切回时 sticky 顶栏不绘制的问题 */
|
|
1950
2137
|
function onResume() {
|
|
1951
2138
|
if (document.visibilityState !== 'visible') return
|
|
2139
|
+
resetRealtimeAfterBackground()
|
|
1952
2140
|
applyNativeInsets()
|
|
1953
2141
|
// 视图状态与 body class 兜底同步(会话页顶栏按设计隐藏, 主页必须恢复显示)
|
|
1954
2142
|
document.body.classList.toggle('in-session', !$('view-session').classList.contains('hidden'))
|
|
@@ -1962,7 +2150,7 @@ function onResume() {
|
|
|
1962
2150
|
updateConn()
|
|
1963
2151
|
void openPendingNavigation()
|
|
1964
2152
|
recoverSessionHistory()
|
|
1965
|
-
if(state.token)openStreams()
|
|
2153
|
+
if (state.token && navigator.onLine) openStreams()
|
|
1966
2154
|
}
|
|
1967
2155
|
|
|
1968
2156
|
/* 回前台 / 定时兜底: 任何流不在 OPEN 就重连; 多服务器时顺便重测速 */
|
|
@@ -1972,7 +2160,7 @@ document.addEventListener('visibilitychange', () => {
|
|
|
1972
2160
|
if (window.NativeBackground?.getPendingNavigation?.()) return
|
|
1973
2161
|
if (state.servers.length) selectFastestServer({ silent: true })
|
|
1974
2162
|
else if (state.token) repairMissingStreams()
|
|
1975
|
-
}
|
|
2163
|
+
} else markRealtimeBackgrounded()
|
|
1976
2164
|
})
|
|
1977
2165
|
window.addEventListener('pageshow', onResume)
|
|
1978
2166
|
setInterval(() => {
|
|
@@ -2265,7 +2453,7 @@ async function refreshSessions() {
|
|
|
2265
2453
|
if (!v) {
|
|
2266
2454
|
// 网关不可达: 用上次成功的会话列表兜底, 用户仍能打开历史缓存
|
|
2267
2455
|
if (!state.sessions.length) {
|
|
2268
|
-
const cached =
|
|
2456
|
+
const cached = readCachedSessions()
|
|
2269
2457
|
if (Array.isArray(cached) && cached.length) {
|
|
2270
2458
|
state.sessions = cached
|
|
2271
2459
|
state.byId = new Map(cached.map(s => [s.sessionId, s]))
|
|
@@ -2284,7 +2472,7 @@ async function refreshSessions() {
|
|
|
2284
2472
|
state.subagentSessions[id] = merged
|
|
2285
2473
|
}
|
|
2286
2474
|
applyPendingProjections()
|
|
2287
|
-
|
|
2475
|
+
writeSessionCache(state.sessions)
|
|
2288
2476
|
if(typeof window!=='undefined')window.DshDoctorEntry?.consumeSessionLink(openSession,state.byId)
|
|
2289
2477
|
renderSessions()
|
|
2290
2478
|
refreshWorkbench()
|
|
@@ -2293,7 +2481,7 @@ async function refreshSessions() {
|
|
|
2293
2481
|
|
|
2294
2482
|
function removeLocalSessionRecord(sessionId) {
|
|
2295
2483
|
if (!sessionId) return
|
|
2296
|
-
void window.DshHistory.cacheRemove(
|
|
2484
|
+
for (const scope of connectionCacheReadKeys('history')) void window.DshHistory.cacheRemove(scope,sessionId)
|
|
2297
2485
|
state.sessions = state.sessions.filter(session => session?.sessionId !== sessionId)
|
|
2298
2486
|
state.byId.delete(sessionId)
|
|
2299
2487
|
state.pendingProjections.delete(sessionId)
|
|
@@ -2302,7 +2490,7 @@ function removeLocalSessionRecord(sessionId) {
|
|
|
2302
2490
|
delete state.queues[sessionId]
|
|
2303
2491
|
delete state.jobs[sessionId]
|
|
2304
2492
|
LS.del(historyCacheScope()) // Also discard the obsolete monolithic cache.
|
|
2305
|
-
|
|
2493
|
+
writeSessionCache(state.sessions)
|
|
2306
2494
|
}
|
|
2307
2495
|
|
|
2308
2496
|
function proj(s, key, d) { return s?.projections?.values?.[key] ?? d }
|
|
@@ -3073,7 +3261,10 @@ async function closeSession() {
|
|
|
3073
3261
|
function bindNativeBack() {
|
|
3074
3262
|
if (!CAP?.isNativePlatform?.()) return
|
|
3075
3263
|
try {
|
|
3076
|
-
CAP.Plugins?.App?.addListener?.('appStateChange',({isActive})=>{
|
|
3264
|
+
CAP.Plugins?.App?.addListener?.('appStateChange', ({ isActive }) => {
|
|
3265
|
+
if (isActive) onResume()
|
|
3266
|
+
else markRealtimeBackgrounded()
|
|
3267
|
+
})
|
|
3077
3268
|
CAP.Plugins?.App?.addListener?.('backButton', () => {
|
|
3078
3269
|
if (typeof window !== 'undefined' && window.DshSlashSuggestions?.close()) return
|
|
3079
3270
|
if ($('composer-wrap')?.classList.contains('fs')) { setComposerFullscreen(false); return }
|
|
@@ -3292,9 +3483,55 @@ function partialReasoningHtml() {
|
|
|
3292
3483
|
}
|
|
3293
3484
|
|
|
3294
3485
|
|
|
3486
|
+
function readSessionCache() {
|
|
3487
|
+
if (typeof readCachedSessions === 'function') return readCachedSessions()
|
|
3488
|
+
const scope = historyCacheScope()
|
|
3489
|
+
if (globalThis.DshSessionCache?.read) return globalThis.DshSessionCache.read(scope)
|
|
3490
|
+
const canonical = cacheRead(CACHE.sessions, null)
|
|
3491
|
+
if (Array.isArray(canonical)) return canonical
|
|
3492
|
+
try {
|
|
3493
|
+
const legacy = JSON.parse(LS.get(scope + ':sessions', ''))
|
|
3494
|
+
if (Array.isArray(legacy)) { cacheWrite(CACHE.sessions, legacy); return legacy }
|
|
3495
|
+
} catch {}
|
|
3496
|
+
return null
|
|
3497
|
+
}
|
|
3498
|
+
function writeSessionCache(list) {
|
|
3499
|
+
const value = Array.isArray(list) ? list.slice(0, 80) : []
|
|
3500
|
+
const keys = typeof connectionCacheReadKeys === 'function' ? connectionCacheReadKeys('sessions') : [CACHE.sessions]
|
|
3501
|
+
let saved = false
|
|
3502
|
+
for (const key of keys) {
|
|
3503
|
+
if (globalThis.DshSessionCache?.writeKey) saved = globalThis.DshSessionCache.writeKey(key, value) || saved
|
|
3504
|
+
else { cacheWrite(key, value); saved = true }
|
|
3505
|
+
}
|
|
3506
|
+
return saved
|
|
3507
|
+
}
|
|
3508
|
+
function clearSessionCache(scope = historyCacheScope()) {
|
|
3509
|
+
if (globalThis.DshSessionCache?.clear) return globalThis.DshSessionCache.clear(scope)
|
|
3510
|
+
try { LS.del(scope.replace(/^historyCacheV2:/, 'sessionsCacheV2:')) } catch {}
|
|
3511
|
+
try { LS.del(scope + ':sessions') } catch {}
|
|
3512
|
+
}
|
|
3513
|
+
function clearAllSessionCaches() {
|
|
3514
|
+
if (globalThis.DshSessionCache?.clearAll) return globalThis.DshSessionCache.clearAll()
|
|
3515
|
+
try {
|
|
3516
|
+
const storage = globalThis.localStorage
|
|
3517
|
+
if (!storage) return false
|
|
3518
|
+
for (const key of Object.keys(storage)) {
|
|
3519
|
+
if (key.startsWith('sessionsCacheV2:') || (key.startsWith('historyCacheV2:') && key.endsWith(':sessions'))) storage.removeItem(key)
|
|
3520
|
+
}
|
|
3521
|
+
return true
|
|
3522
|
+
} catch { return false }
|
|
3523
|
+
}
|
|
3524
|
+
|
|
3295
3525
|
function restoreCachedSessionList() {
|
|
3296
|
-
if(state.sessions.length)return
|
|
3297
|
-
try
|
|
3526
|
+
if (state.sessions.length) return
|
|
3527
|
+
try {
|
|
3528
|
+
const items = readSessionCache()
|
|
3529
|
+
state.sessions = Array.isArray(items) ? items.filter(item => typeof item?.sessionId === 'string').slice(0, 80) : []
|
|
3530
|
+
state.byId = new Map(state.sessions.map(item => [item.sessionId, item]))
|
|
3531
|
+
// Render even when no cache exists: an identity switch must clear the old
|
|
3532
|
+
// connection's list instead of leaving its DOM behind.
|
|
3533
|
+
renderSessions()
|
|
3534
|
+
} catch {}
|
|
3298
3535
|
}
|
|
3299
3536
|
|
|
3300
3537
|
let conversationView = null
|
|
@@ -3326,15 +3563,21 @@ function scheduleHistoryCacheSave() {
|
|
|
3326
3563
|
}
|
|
3327
3564
|
async function saveHistoryCache(scope=historyCacheScope(),id=state.current,history=state.history) {
|
|
3328
3565
|
if(!id||!history.visible.length||history.tailEvicted)return
|
|
3329
|
-
const saved=await window.DshHistory.cacheSave(scope,id,{title:titleOf(state.byId.get(id)),events:history.visible
|
|
3566
|
+
const saved=await window.DshHistory.cacheSave(scope,id,{title:titleOf(state.byId.get(id)),events:history.visible,minSeq:history.minSeq,hasMore:history.hasMore,partialReasoning:[...history.partialReasoning.values()]},250)
|
|
3330
3567
|
if(!saved&&state.current===id&&state.history===history&&scope===historyCacheScope())historySource('saveFailed')
|
|
3331
3568
|
if(saved&&state.current===id&&state.history===history&&scope===historyCacheScope()&&['synced','saveFailed'].includes(history.source))historySource('saved')
|
|
3332
3569
|
}
|
|
3333
3570
|
async function restoreCachedHistory() {
|
|
3334
|
-
const connection=captureConnection(),id=state.current,history=state.history
|
|
3571
|
+
const connection=captureConnection(),id=state.current,history=state.history
|
|
3335
3572
|
if(!id)return false
|
|
3336
|
-
const
|
|
3337
|
-
|
|
3573
|
+
const valid = () => connection.valid() && state.current === id && state.history === history && (!history.loaded || history.cached)
|
|
3574
|
+
let cached
|
|
3575
|
+
for (const scope of connectionCacheReadKeys('history')) {
|
|
3576
|
+
cached = await window.DshHistory.cacheLoad(scope,id,legacyId=>window.DshHistory.decodeLegacy(LS.get(scope,''),legacyId))
|
|
3577
|
+
if (!valid()) return false
|
|
3578
|
+
if (cached?.events?.length) break
|
|
3579
|
+
}
|
|
3580
|
+
if (!cached?.events?.length) return false
|
|
3338
3581
|
history.visible=cached.events.slice(-250).filter(entry=>entry?.seq!=null&&shouldShowEvent(entry.event?.type,entry.event)).sort((a,b)=>a.seq-b.seq)
|
|
3339
3582
|
history.seqs=new Set(history.visible.map(entry=>entry.seq));history.loaded=true;history.cached=true;history.hasMore=cached.events.length>250||cached.hasMore!==false;history.minSeq=cached.events.length>250?(history.visible[0]?.seq??Infinity):Number.isFinite(cached.minSeq)?cached.minSeq:history.visible[0]?.seq??Infinity
|
|
3340
3583
|
if(cached.title&&!hasSessionTitle(state.byId.get(id)))hydrateSessionProjections(id,{values:{title:cached.title},asOfSeq:0})
|
|
@@ -3426,7 +3669,7 @@ async function loadHistory(reset = true) {
|
|
|
3426
3669
|
history.renderError=!!getConversationView().renderErrors
|
|
3427
3670
|
historySource(history.renderError?'error':'synced');setSessionRecovery(history.renderError?'error':'ready')
|
|
3428
3671
|
if(approvalChanged)renderApprovalRecords()
|
|
3429
|
-
$('history-hint').textContent=t('history.count',{n:history.visible.filter(entry
|
|
3672
|
+
$('history-hint').textContent=t('history.count',{n:history.visible.filter(entry=>entry.event?.type==='user/message'||entry.event?.type==='assistant/message').length})
|
|
3430
3673
|
diagnostic?.end({phase:history.renderError?'failed':'rendered',count:history.visible.length,renderedCount:getConversationView().end-getConversationView().start,renderErrors:getConversationView().renderErrors||0})
|
|
3431
3674
|
if(!history.renderError)scheduleHistoryCacheSave()
|
|
3432
3675
|
} catch(error) { failLoad(error,true) }
|
|
@@ -3503,7 +3746,7 @@ function renderHistory(reset=false,mode='auto') {
|
|
|
3503
3746
|
const filtered=filteredEntries(),toolNames=new Map()
|
|
3504
3747
|
for(const entry of state.history.visible){const d=entry.event?.data;if(entry.event?.type==='tool/call'&&d?.callId&&d.name)toolNames.set(d.callId,d.name)}
|
|
3505
3748
|
state.history.toolNames=toolNames
|
|
3506
|
-
$('history-hint').textContent=t('history.count',{n:state.history.visible.filter(entry
|
|
3749
|
+
$('history-hint').textContent=t('history.count',{n:state.history.visible.filter(entry=>entry.event?.type==='user/message'||entry.event?.type==='assistant/message').length})
|
|
3507
3750
|
let prepared=window.DshActivity?.prepare(filtered)||filtered
|
|
3508
3751
|
// 弱网精简:尚未返回的调用在完成前不展示,只留已完成的消息与工具结果。
|
|
3509
3752
|
if(weakStreamTrim())prepared=prepared.filter(entry=>entry.event?.type!=='tool/call'||entry.view?.toolActivity)
|
|
@@ -4699,8 +4942,11 @@ function planReviewSnapshot(sessionId) {
|
|
|
4699
4942
|
|
|
4700
4943
|
function updatePlanReviewVisibility(view) {
|
|
4701
4944
|
if (!planReviewHost) return
|
|
4702
|
-
|
|
4703
|
-
|
|
4945
|
+
// The controller decides whether a disconnected session still has a plan to show.
|
|
4946
|
+
const decide = window.DshPlanReview?.hasContent
|
|
4947
|
+
const visible = typeof decide === 'function'
|
|
4948
|
+
? !!decide(view)
|
|
4949
|
+
: !!(view?.plan?.supported || view?.review || (Array.isArray(view?.plans) && view.plans.length))
|
|
4704
4950
|
planReviewHost.classList.toggle('hidden', !visible)
|
|
4705
4951
|
}
|
|
4706
4952
|
|
|
@@ -5618,7 +5864,7 @@ function renderQueue() {
|
|
|
5618
5864
|
updateCancelBtn()
|
|
5619
5865
|
updateSessionStatus()
|
|
5620
5866
|
// 队列数量在会话列表已显示; 详情页不重复大 UI
|
|
5621
|
-
$('history-hint').textContent = items.length ? t('history.queueAndCount', { q: items.length, n: state.history.visible.filter(entry
|
|
5867
|
+
$('history-hint').textContent = items.length ? t('history.queueAndCount', { q: items.length, n: state.history.visible.filter(entry=>entry.event?.type==='user/message'||entry.event?.type==='assistant/message').length }) : t('history.countOnly', { n: state.history.visible.filter(entry=>entry.event?.type==='user/message'||entry.event?.type==='assistant/message').length })
|
|
5622
5868
|
renderSessions()
|
|
5623
5869
|
}
|
|
5624
5870
|
|
|
@@ -6558,16 +6804,35 @@ function toggleUpdateExpand() {
|
|
|
6558
6804
|
}
|
|
6559
6805
|
|
|
6560
6806
|
async function loadLocalVersion() {
|
|
6561
|
-
|
|
6562
|
-
|
|
6563
|
-
|
|
6564
|
-
|
|
6565
|
-
|
|
6566
|
-
|
|
6567
|
-
|
|
6568
|
-
|
|
6569
|
-
|
|
6570
|
-
|
|
6807
|
+
if (loadLocalVersion._promise) return loadLocalVersion._promise
|
|
6808
|
+
const job = (async () => {
|
|
6809
|
+
try {
|
|
6810
|
+
const read = async signal => {
|
|
6811
|
+
const res = await fetch('version.json?t=' + Date.now(), { cache: 'no-store', signal })
|
|
6812
|
+
if (!res.ok) return ''
|
|
6813
|
+
return String((await res.json())?.version || '')
|
|
6814
|
+
}
|
|
6815
|
+
let version = ''
|
|
6816
|
+
if (globalThis.DshNetwork?.readWithDeadline) {
|
|
6817
|
+
// Deadline covers the body read as well as the response headers.
|
|
6818
|
+
version = await globalThis.DshNetwork.readWithDeadline(read, 1500)
|
|
6819
|
+
} else {
|
|
6820
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null
|
|
6821
|
+
const timer = controller ? setTimeout(() => controller.abort(), 1500) : null
|
|
6822
|
+
try { version = await read(controller?.signal) } finally { if (timer) clearTimeout(timer) }
|
|
6823
|
+
}
|
|
6824
|
+
if (version) state.localVersion = version
|
|
6825
|
+
} catch {}
|
|
6826
|
+
if (!state.localVersion && CAP?.isNativePlatform?.()) {
|
|
6827
|
+
state.localVersion = (window.NativeUpdate?.getInstalledVersion?.() || '').replace(/\.rc\.(\d+)$/, '-rc.$1')
|
|
6828
|
+
}
|
|
6829
|
+
const drawerVersion = $('group-drawer-version')
|
|
6830
|
+
if (drawerVersion) drawerVersion.textContent = state.localVersion ? 'v' + state.localVersion : '—'
|
|
6831
|
+
$('update-desc').textContent = state.localVersion ? t('update.currentV', { version: state.localVersion }) : t('update.noVersion')
|
|
6832
|
+
return state.localVersion
|
|
6833
|
+
})()
|
|
6834
|
+
loadLocalVersion._promise = job
|
|
6835
|
+
try { return await job } finally { if (loadLocalVersion._promise === job) loadLocalVersion._promise = null }
|
|
6571
6836
|
}
|
|
6572
6837
|
|
|
6573
6838
|
/* ---------------- 远程公告 ----------------
|
|
@@ -8452,6 +8717,8 @@ function applyPairUrl(url, options = {}) {
|
|
|
8452
8717
|
state.servers.unshift({ id: newServerId(), url: server, note: '', group: state.activeGroup, token: tok })
|
|
8453
8718
|
}
|
|
8454
8719
|
}
|
|
8720
|
+
// Pairing carries one credential for every address it lists.
|
|
8721
|
+
syncGroupToken(state.activeGroup, tok)
|
|
8455
8722
|
const first = state.servers.find(s => s.url === servers[0] && normalizedServerToken(s.token) === tok)
|
|
8456
8723
|
if (!first) return false
|
|
8457
8724
|
if (previousServer !== first.url || previousToken !== tok) resetFsForServer()
|
|
@@ -8464,7 +8731,7 @@ function applyPairUrl(url, options = {}) {
|
|
|
8464
8731
|
$('token-desc').textContent = t('token.savedScan')
|
|
8465
8732
|
syncBgConfig()
|
|
8466
8733
|
const setupId = u.searchParams.get('relaySetup')
|
|
8467
|
-
if (/^[a-f0-9]{32}$/.test(setupId || '') && window.NativeE2ee?.configure) {
|
|
8734
|
+
if (!globalThis.DSH_REMOTE_E2EE_DISABLED && /^[a-f0-9]{32}$/.test(setupId || '') && window.NativeE2ee?.configure) {
|
|
8468
8735
|
relaySetup = { id: setupId, token: tok, servers }
|
|
8469
8736
|
showView('view-settings')
|
|
8470
8737
|
showSettingsPage('cloud-relay')
|
|
@@ -8752,6 +9019,35 @@ function bindNativeLinks() {
|
|
|
8752
9019
|
} catch {}
|
|
8753
9020
|
}
|
|
8754
9021
|
|
|
9022
|
+
function disableE2eeState() {
|
|
9023
|
+
try { window.NativeE2ee?.clear?.() } catch {}
|
|
9024
|
+
let changed = false, removedCurrent = false
|
|
9025
|
+
state.servers = state.servers.filter(server => {
|
|
9026
|
+
const current = server.url === state.server && serverToken(server) === state.token
|
|
9027
|
+
// Remove only the auto-added encrypted public address; keep its LAN sibling.
|
|
9028
|
+
if (server.cacheRelayOrigin && server.url === server.cacheRelayOrigin) {
|
|
9029
|
+
changed = true
|
|
9030
|
+
if (current) removedCurrent = true
|
|
9031
|
+
return false
|
|
9032
|
+
}
|
|
9033
|
+
if (server.cacheRelayOrigin || server.cacheRelayPin) {
|
|
9034
|
+
delete server.cacheRelayOrigin
|
|
9035
|
+
delete server.cacheRelayPin
|
|
9036
|
+
changed = true
|
|
9037
|
+
}
|
|
9038
|
+
return true
|
|
9039
|
+
})
|
|
9040
|
+
if (!changed) return
|
|
9041
|
+
if (removedCurrent) {
|
|
9042
|
+
const first = state.servers[0]
|
|
9043
|
+
state.server = first?.url || ''
|
|
9044
|
+
state.token = first ? serverToken(first) : ''
|
|
9045
|
+
if (state.token) LS.set('token', state.token)
|
|
9046
|
+
else LS.del('token')
|
|
9047
|
+
}
|
|
9048
|
+
saveServers()
|
|
9049
|
+
}
|
|
9050
|
+
|
|
8755
9051
|
function initToken() {
|
|
8756
9052
|
const urlToken = new URLSearchParams(location.search).get('token')
|
|
8757
9053
|
if (urlToken) {
|
|
@@ -8771,6 +9067,7 @@ function initToken() {
|
|
|
8771
9067
|
if (current) current.token = state.token
|
|
8772
9068
|
saveServers()
|
|
8773
9069
|
}
|
|
9070
|
+
if (globalThis.DSH_REMOTE_E2EE_DISABLED === true) disableE2eeState()
|
|
8774
9071
|
$('token-desc').textContent = state.token ? t('token.savedLocal') : t('token.notSet')
|
|
8775
9072
|
$('server-desc').textContent = state.server || t('servers.defaultDesc')
|
|
8776
9073
|
}
|
|
@@ -9706,7 +10003,11 @@ async function boot() {
|
|
|
9706
10003
|
applyNativeInsets()
|
|
9707
10004
|
showView('view-activity')
|
|
9708
10005
|
updateConn()
|
|
9709
|
-
|
|
10006
|
+
// Restore the startup connection's list before any network wait. The
|
|
10007
|
+
// connection setter also queues a restore, but it must not be the only path:
|
|
10008
|
+
// an identity switch has to clear the old DOM even when the new scope is empty.
|
|
10009
|
+
if (state.token) restoreCachedSessionList()
|
|
10010
|
+
const versionReady = loadLocalVersion()
|
|
9710
10011
|
if (!state.token) {
|
|
9711
10012
|
showView('view-activity')
|
|
9712
10013
|
overviewStarting=false
|
|
@@ -9714,9 +10015,11 @@ async function boot() {
|
|
|
9714
10015
|
} else {
|
|
9715
10016
|
// 多服务器: 启动时静默测速一次, 选最快的连接(同源页面也参与比较)
|
|
9716
10017
|
if (!doctorSessionHandoff) await selectFastestServer({ silent: true, reconnect: false })
|
|
9717
|
-
await maybeWarnAppBehindGateway({ probe: true })
|
|
9718
10018
|
overviewStarting=false
|
|
9719
10019
|
openStreams()
|
|
10020
|
+
// The version read is only for update prompts and announcements. Do not
|
|
10021
|
+
// hold streams or session refresh behind it; 1.5s is enforced inside.
|
|
10022
|
+
void versionReady.then(() => maybeWarnAppBehindGateway({ probe: true })).catch(() => {})
|
|
9720
10023
|
await Promise.all([refreshAll(),refreshHostDescription()])
|
|
9721
10024
|
loadDshControl()
|
|
9722
10025
|
}
|
|
@@ -9762,16 +10065,16 @@ function mountWorkflow() {
|
|
|
9762
10065
|
command: runSlashCommand, refresh: refreshAll, retry: () => { openStreams(); startOverviewDetection(true); void refreshAll() },
|
|
9763
10066
|
operations: () => { const connection=captureConnection(); return { url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid } },
|
|
9764
10067
|
relay: () => { const connection=captureConnection(); return { url:()=>adminApiUrl('/admin/api/relay'),headers:{authorization:'Bearer '+connection.token,...clientIdHeaders()},valid:connection.valid,connected:!!connection.token,setupId:relaySetupFor(connection) } },
|
|
9765
|
-
syncRelayActivation: CAP?.isNativePlatform?.() ? status => syncRelayActivation(status.activationId, true) : undefined,
|
|
9766
|
-
e2eeAutoPaired: saveAutoPairedRelay,
|
|
9767
|
-
e2eeScan: () => scanPair('CAMERA'),
|
|
9768
|
-
e2eeConnect: (origin, connection) => {
|
|
10068
|
+
syncRelayActivation: globalThis.DSH_REMOTE_E2EE_DISABLED !== true && CAP?.isNativePlatform?.() ? status => syncRelayActivation(status.activationId, true) : undefined,
|
|
10069
|
+
e2eeAutoPaired: globalThis.DSH_REMOTE_E2EE_DISABLED === true ? undefined : saveAutoPairedRelay,
|
|
10070
|
+
e2eeScan: globalThis.DSH_REMOTE_E2EE_DISABLED === true ? undefined : () => scanPair('CAMERA'),
|
|
10071
|
+
e2eeConnect: globalThis.DSH_REMOTE_E2EE_DISABLED === true ? undefined : (origin, connection) => {
|
|
9769
10072
|
if (!connection.valid()) return
|
|
9770
10073
|
const token = connection.headers.authorization.slice(7)
|
|
9771
10074
|
closeStream('mux'); closeStream('host'); stopPolling(); state.wsTicket = null
|
|
9772
10075
|
if (applyPairUrl('dshremote://pair?' + new URLSearchParams({ server: origin, token }).toString())) { void refreshAll(); openStreams() }
|
|
9773
10076
|
},
|
|
9774
|
-
e2eeModeChange: (origin, connection) => {
|
|
10077
|
+
e2eeModeChange: globalThis.DSH_REMOTE_E2EE_DISABLED === true ? undefined : (origin, connection) => {
|
|
9775
10078
|
if (!connection.valid() || new URL(apiUrl('/relay'),location.href).origin !== origin) return
|
|
9776
10079
|
closeStream('mux'); closeStream('host'); stopPolling(); state.wsTicket = null
|
|
9777
10080
|
syncBgConfig(); void refreshAll(); openStreams()
|
|
@@ -9845,6 +10148,7 @@ async function clearWorkflowData(kind) {
|
|
|
9845
10148
|
if(kind!=='images')cancelHistoryLoad()
|
|
9846
10149
|
const results=[]
|
|
9847
10150
|
if(kind!=='images')results.push(await window.DshHistory.cacheClear())
|
|
10151
|
+
if(kind!=='images')results.push(clearAllSessionCaches())
|
|
9848
10152
|
if(kind!=='history')results.push(await window.DshImageCache.clear())
|
|
9849
10153
|
if(results.includes(false))return toast(english?'Some caches could not be cleared. Retry shortly.':'部分缓存未能清除,请稍后重试。','err')
|
|
9850
10154
|
return toast(english ? 'Cache cleared' : '缓存已清除', 'ok')
|
|
@@ -9853,14 +10157,17 @@ async function clearWorkflowData(kind) {
|
|
|
9853
10157
|
window.NativeBackground?.savePeakReminderConfig?.(JSON.stringify({ enabled:false }))
|
|
9854
10158
|
window.NativeBackground?.setPendingNotificationsEnabled?.(false)
|
|
9855
10159
|
if (kind === 'connection') {
|
|
9856
|
-
const connection=captureConnection(),
|
|
10160
|
+
const connection = captureConnection(), scopes = connectionCacheReadKeys('history')
|
|
9857
10161
|
cancelHistoryLoad()
|
|
9858
|
-
await
|
|
9859
|
-
|
|
10162
|
+
await Promise.all(scopes.flatMap(scope => [
|
|
10163
|
+
window.DshImageCache.clear(scope),
|
|
10164
|
+
window.DshHistory.cacheClear(scope),
|
|
10165
|
+
clearSessionCache(scope),
|
|
10166
|
+
]))
|
|
9860
10167
|
if(!connection.valid())return
|
|
9861
10168
|
const current = currentServerEntry()
|
|
9862
10169
|
const remaining = current ? state.servers.filter(server => server.id !== current.id) : state.servers
|
|
9863
|
-
if (!remaining.some(server => server.url === state.server) && window.NativeE2ee?.remove?.(state.server) === false) return toast(english ? 'Unable to remove encrypted pairing.' : '加密配对未能清理,请重试。','err')
|
|
10170
|
+
if (globalThis.DSH_REMOTE_E2EE_DISABLED !== true && !remaining.some(server => server.url === state.server) && window.NativeE2ee?.remove?.(state.server) === false) return toast(english ? 'Unable to remove encrypted pairing.' : '加密配对未能清理,请重试。','err')
|
|
9864
10171
|
if (current) state.servers = state.servers.filter(server => server.id !== current.id)
|
|
9865
10172
|
state.groupActive[state.activeGroup] = ''
|
|
9866
10173
|
state.token = ''; state.server = ''; LS.del('token'); LS.del('server'); saveServers()
|
|
@@ -9872,9 +10179,10 @@ async function clearWorkflowData(kind) {
|
|
|
9872
10179
|
clearTimeout(scheduleHistoryCacheSave._t)
|
|
9873
10180
|
await window.DshHistory.cacheClear()
|
|
9874
10181
|
await window.DshImageCache.clear()
|
|
10182
|
+
clearAllSessionCaches()
|
|
9875
10183
|
resetAnnouncementStorage()
|
|
9876
10184
|
window.DshWorkflow.clearStorage()
|
|
9877
|
-
if (window.NativeE2ee?.clear?.() === false) return toast(english ? 'Encrypted pairing could not be cleared. Retry.' : '加密配对未能清理,请重试。','err')
|
|
10185
|
+
if (globalThis.DSH_REMOTE_E2EE_DISABLED !== true && window.NativeE2ee?.clear?.() === false) return toast(english ? 'Encrypted pairing could not be cleared. Retry.' : '加密配对未能清理,请重试。','err')
|
|
9878
10186
|
location.reload()
|
|
9879
10187
|
}
|
|
9880
10188
|
|
|
@@ -9924,7 +10232,7 @@ globalThis.DshApprovalSummary?.mount({ capture: captureConnection, items: () =>
|
|
|
9924
10232
|
url: (connection, path) => connection.server + path,
|
|
9925
10233
|
headers: connection => ({ authorization: 'Bearer ' + connection.token, ...clientIdHeaders() }) })
|
|
9926
10234
|
globalThis.DshCacheUpgrade?.mount({
|
|
9927
|
-
scopes:()=>state.servers.
|
|
10235
|
+
scopes:()=>state.servers.flatMap(server=>connectionCacheReadKeys('history',server.url,serverToken(server))),
|
|
9928
10236
|
safe:()=>!state.current&&!state.approvals.length&&!state.questions.length&&!composerSending
|
|
9929
10237
|
&&![...document.querySelectorAll('textarea,input:not([type="checkbox"]):not([type="radio"])')].some(input=>input.getBoundingClientRect().width&&input.value)
|
|
9930
10238
|
&&!document.querySelector('[data-transfer-id]')&&!state.sessions.some(session=>session.running)
|