dsh-remote-plugin 0.8.8 → 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/README.en.md +16 -5
- package/README.md +15 -4
- package/apk/dsh-remote.apk +0 -0
- package/gateway.cjs +583 -84
- package/index.mjs +1 -0
- package/package.json +8 -3
- package/public/activity.js +97 -10
- package/public/admin.html +34 -33
- package/public/admin.js +10 -2
- package/public/announcements.json +36 -0
- package/public/app.js +1564 -226
- package/public/bc-integration.css +81 -0
- package/public/build.json +2 -2
- package/public/composer-tools.css +184 -0
- package/public/composer-tools.js +888 -0
- package/public/desktop/desktop.html +94 -73
- package/public/desktop/desktop.js +726 -83
- package/public/e2ee-config.js +5 -0
- package/public/e2ee-transport.js +23 -4
- package/public/file-inbox.js +77 -18
- package/public/genui.css +10 -0
- package/public/genui.js +22 -4
- package/public/history.js +114 -17
- package/public/host-queue.js +232 -0
- package/public/host-schedule.js +301 -0
- package/public/host-state.css +19 -0
- package/public/index.html +332 -140
- package/public/md.js +21 -1
- package/public/network.js +33 -1
- package/public/onboarding.js +3 -3
- package/public/operations.js +4 -3
- package/public/plan-review.css +297 -0
- package/public/plan-review.js +642 -0
- package/public/plugin.html +29 -28
- package/public/relay-autopair.js +30 -10
- package/public/relay-devices.js +7 -3
- package/public/relay-settings.css +11 -0
- package/public/relay-settings.js +372 -30
- package/public/session-cache.js +85 -0
- package/public/session-management.css +61 -0
- package/public/session-management.js +742 -0
- package/public/session-search.css +137 -0
- package/public/session-search.js +977 -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/SOURCES.json +10 -0
- package/public/skins/miku/chibi.png +0 -0
- package/public/skins/miku/preview.html +33 -0
- package/public/skins/miku/skin.css +82 -0
- 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/slash-suggestions.js +15 -3
- package/public/sponsor-entry.js +11 -3
- package/public/styles.css +141 -21
- package/public/subagents.css +5 -0
- package/public/subagents.js +52 -0
- package/public/theme-vars.css +65 -1
- package/public/theme.js +4 -3
- package/public/turn-diff.css +323 -0
- package/public/turn-diff.js +778 -0
- package/public/update.json +12 -12
- package/public/version.json +1 -1
- package/public/workflow.css +305 -34
- package/public/workflow.js +141 -41
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
|
}
|
|
@@ -77,7 +107,6 @@ const state = {
|
|
|
77
107
|
approvalRecordsServer: null,
|
|
78
108
|
questions: [], // 待处理提问
|
|
79
109
|
queues: {}, // sessionId -> queue items
|
|
80
|
-
queueSteering: {}, // sessionId:itemId -> pending steer request
|
|
81
110
|
compactionBootAt: Date.now(),
|
|
82
111
|
compactions: {}, // sessionId -> {active, phase, startedAt, message, source}
|
|
83
112
|
pendingCommands: {}, // sessionId -> command name; waits briefly before showing generic progress
|
|
@@ -104,6 +133,7 @@ const state = {
|
|
|
104
133
|
wb: null,
|
|
105
134
|
wbProjects: [],
|
|
106
135
|
wbArchived: [],
|
|
136
|
+
wbPinned: [],
|
|
107
137
|
wbOpen: false,
|
|
108
138
|
wbOpenProjects: {},
|
|
109
139
|
subagentSessions: {}
|
|
@@ -125,16 +155,27 @@ for (const key of ['server', 'token']) {
|
|
|
125
155
|
clearTimeout(state.refreshTimer); state.refreshTimer = null
|
|
126
156
|
state.sessions = []; state.byId.clear(); state.pendingProjections.clear(); state.runtimeErrors = new Map()
|
|
127
157
|
state.hostInfo = null
|
|
128
|
-
if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){
|
|
158
|
+
if (typeof closeStream === 'function' && typeof streamMeta !== 'undefined') {
|
|
159
|
+
stopPolling()
|
|
160
|
+
clearReconnect()
|
|
161
|
+
for (const kind of ['mux', 'host']) {
|
|
162
|
+
closeStream(kind)
|
|
163
|
+
streamMeta[kind].attempt = 0
|
|
164
|
+
streamMeta[kind].failures = 0
|
|
165
|
+
}
|
|
166
|
+
state.streamMode = 'ws'
|
|
167
|
+
state.pollSeq = { mux: 0, host: 0 }
|
|
168
|
+
state.errCount = 0
|
|
169
|
+
}
|
|
129
170
|
state.current = null; state.history = emptyHistory(); state.subagentSessions = {}; window.DshSubagents?.reset()
|
|
130
171
|
state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
|
|
131
172
|
state.modelSettings = { status: 'idle', error: '', writable: false, hasDocument: false, providers: [], namespaces: [], credentials: {} }; state.modelEditor = null
|
|
132
173
|
state.goalEdit = null; state.goalEditContext = null
|
|
133
174
|
state.approvals = []; state.questions = []; state.questionModal = null
|
|
134
|
-
state.queues = {}; state.jobs = {}; state.
|
|
175
|
+
state.queues = {}; state.jobs = {}; state.compactions = {}; state.compactionTerminals = {}; state.compactionSeqs = {}; state.compactionBootAt = Date.now(); state.pendingCommands = {}; state.sessionTurnTimes = {}
|
|
135
176
|
state.sessionActivity = new Set(); state.pendingPrompts = new Set()
|
|
136
177
|
state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
|
|
137
|
-
state.wb = null; state.wbProjects = []; state.wbArchived = []; state.workspaceFilter = ''; state.fs.workspaceId = ''; clearTimeout(scheduleHistoryCacheSave._t)
|
|
178
|
+
state.wb = null; state.wbProjects = []; state.wbArchived = []; state.wbPinned = []; state.workspaceFilter = ''; state.fs.workspaceId = ''; clearTimeout(scheduleHistoryCacheSave._t)
|
|
138
179
|
window.DshPluginCenter?.close()
|
|
139
180
|
window.DshInsights?.close()
|
|
140
181
|
window.DshExtensions?.close()
|
|
@@ -145,7 +186,11 @@ for (const key of ['server', 'token']) {
|
|
|
145
186
|
if (typeof document !== 'undefined') document.getElementById('btn-insights')?.classList.add('hidden')
|
|
146
187
|
if(typeof document!=='undefined') {
|
|
147
188
|
const identityGeneration=connectionGeneration
|
|
148
|
-
queueMicrotask(()=>{
|
|
189
|
+
queueMicrotask(() => {
|
|
190
|
+
if (identityGeneration !== connectionGeneration) return
|
|
191
|
+
if (typeof groupDrawerOpen === 'function' && groupDrawerOpen() && $('group-drawer').dataset.panel) closeGroupDrawer()
|
|
192
|
+
if (typeof startOverviewDetection === 'function') startOverviewDetection(true, true)
|
|
193
|
+
})
|
|
149
194
|
document.getElementById('history')?.replaceChildren?.()
|
|
150
195
|
const generation=connectionGeneration
|
|
151
196
|
queueMicrotask(()=>{if(generation!==connectionGeneration)return;if(typeof conversationView!=='undefined')conversationView?.reset();if(!state.current&&document.body.classList.contains('in-session')){document.body.classList.remove('in-session');showView('view-home')};restoreCachedSessionList()})
|
|
@@ -186,6 +231,7 @@ function toast(text, kind = '') {
|
|
|
186
231
|
/* ---------------- 应用内选择抽屉 ---------------- */
|
|
187
232
|
const CUSTOM_SELECT_TITLES = {
|
|
188
233
|
'session-workspace-filter': 'workspace.select',
|
|
234
|
+
'session-search-workspace': 'workspace.select',
|
|
189
235
|
'session-sort': 'sessions.sortLabel',
|
|
190
236
|
'fs-workspace': 'workspace.select',
|
|
191
237
|
'mobile-enter-action': 'settings.mobileEnterTitle',
|
|
@@ -310,7 +356,10 @@ function initCustomSelects() {
|
|
|
310
356
|
$('custom-select-close').addEventListener('click', () => closeCustomSelect())
|
|
311
357
|
$('custom-select-cancel').addEventListener('click', () => closeCustomSelect())
|
|
312
358
|
document.addEventListener('keydown', (event) => {
|
|
313
|
-
if (event.key === 'Escape' && customSelectCurrent)
|
|
359
|
+
if (event.key === 'Escape' && customSelectCurrent) {
|
|
360
|
+
event.preventDefault()
|
|
361
|
+
closeCustomSelect()
|
|
362
|
+
}
|
|
314
363
|
})
|
|
315
364
|
}
|
|
316
365
|
|
|
@@ -363,7 +412,7 @@ function openDoctor() {
|
|
|
363
412
|
})
|
|
364
413
|
}
|
|
365
414
|
function openFeedbackModal(options = {}) {
|
|
366
|
-
if (!options.preserveDraft) {
|
|
415
|
+
if (!options.preserveDraft && !state.feedbackConnectionRejected) {
|
|
367
416
|
state.feedbackType = 'bug'
|
|
368
417
|
document.querySelectorAll('#fb-chips .fb-chip').forEach(b => b.classList.toggle('current', b.dataset.fbType === 'bug'))
|
|
369
418
|
$('fb-msg').value = ''
|
|
@@ -428,6 +477,7 @@ async function submitFeedback() {
|
|
|
428
477
|
let json = {}
|
|
429
478
|
try { json = await res.json() } catch {}
|
|
430
479
|
if (res.ok && json.ok) { closeFeedbackModal(); openFeedbackSuccess()
|
|
480
|
+
state.feedbackConnectionRejected = false
|
|
431
481
|
const status=$('feedback-diagnostics-status'),saved=json.diagnostics?.saved===true&&json.diagnostics.reportId===clientDiagnostics?.reportId
|
|
432
482
|
status.textContent=clientDiagnostics?(saved?(I18N.lang==='en'?'Diagnostic report saved. ID: ':'诊断日志已保存,编号:')+clientDiagnostics.reportId:(I18N.lang==='en'?'Feedback received, but the server did not confirm the complete diagnostic report. Copy or export the local log to supplement it.':'反馈已收到,但服务器未确认完整诊断日志已保存。请复制或导出本地日志补充。')):''
|
|
433
483
|
status.classList.toggle('hidden',!clientDiagnostics)
|
|
@@ -438,6 +488,10 @@ async function submitFeedback() {
|
|
|
438
488
|
else if (json.error === 'collector-body-limit') { toast(I18N.lang === 'en' ? 'The collector rejected the request size. Your full text is preserved; copy it before updating the collector.' : '收集器请求体超限,全文已保留;请先复制,待收集器升级后再提交。', 'err') }
|
|
439
489
|
else if (json.error === 'feedback_service_unavailable') { toast(I18N.lang === 'en' ? 'Delivery is unconfirmed; it may have been received. Your text is preserved. Check before resubmitting.' : '发送结果未确认,可能已收到。全文已保留,请先核对,勿重复提交。', 'err') }
|
|
440
490
|
else if (json.error === 'feedback-content-unconfirmed') { toast(I18N.lang === 'en' ? 'The content receipt did not match. It may have been received; check before resubmitting. Your text is preserved.' : '正文保存回执不一致,可能已收到;请先核对,勿重复提交。全文已保留。', 'err') }
|
|
491
|
+
else if (res.status === 401 || res.status === 426) {
|
|
492
|
+
state.feedbackConnectionRejected = true
|
|
493
|
+
toast(t('conn.feedbackBlocked'), 'err')
|
|
494
|
+
}
|
|
441
495
|
else { toast(t('feedback.submitFailed', { msg: json.error || res.status }), 'err') }
|
|
442
496
|
} catch(error) {
|
|
443
497
|
diagnostic?.fail(error)
|
|
@@ -493,26 +547,67 @@ function fmtFullTime(ts) {
|
|
|
493
547
|
|
|
494
548
|
/* ---------------- API ---------------- */
|
|
495
549
|
function saveAutoPairedRelay(origin, connection) {
|
|
496
|
-
if (!connection.valid()) return
|
|
550
|
+
if (globalThis.DSH_REMOTE_E2EE_DISABLED === true || !connection.valid()) return
|
|
497
551
|
const token=connection.headers.authorization.slice(7)
|
|
498
|
-
|
|
499
|
-
|
|
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
|
|
500
577
|
saveServers();renderServers();syncBgConfig()
|
|
501
|
-
|
|
578
|
+
if (linked) restoreCachedSessionList()
|
|
579
|
+
if (added) toast(I18N.lang==='en'?'Public access verified. LAN remains connected.':'公网已验证,局域网连接保留。','ok')
|
|
502
580
|
}
|
|
503
581
|
let relaySetup = null
|
|
504
582
|
function relaySetupFor(connection) {
|
|
505
583
|
if (relaySetup && relaySetup.token === connection.token && relaySetup.servers.includes(connection.server)) return relaySetup.id
|
|
506
584
|
return ''
|
|
507
585
|
}
|
|
508
|
-
function offerLocalRelayPairing(connection=captureConnection(), force=false) {
|
|
586
|
+
function offerLocalRelayPairing(connection=captureConnection(), force=false, activationId='') {
|
|
587
|
+
if (globalThis.DSH_REMOTE_E2EE_DISABLED === true) return
|
|
509
588
|
if (!connection.token || !connection.valid()) return
|
|
510
589
|
return window.DshRelayAutoPair?.offer({
|
|
511
590
|
connection:()=>({valid:connection.valid,url:path=>connection.server+path,headers:{authorization:'Bearer '+connection.token},setupId:relaySetupFor(connection)}),
|
|
512
|
-
onPaired:saveAutoPairedRelay,force,
|
|
591
|
+
onPaired:saveAutoPairedRelay,force,activationId,
|
|
513
592
|
onStatus:(message,error)=>{if(force&&error&&connection.valid())toast(message,'err')},
|
|
514
593
|
})
|
|
515
594
|
}
|
|
595
|
+
let relayActivationSync = null
|
|
596
|
+
function syncRelayActivation(activationId, force = false) {
|
|
597
|
+
if (globalThis.DSH_REMOTE_E2EE_DISABLED === true) return
|
|
598
|
+
if (!CAP?.isNativePlatform?.() || !/^[a-f0-9]{32}$/.test(activationId || '')) return
|
|
599
|
+
if (relayActivationSync?.id === activationId && relayActivationSync.connection.valid()) return relayActivationSync.task
|
|
600
|
+
const connection = captureConnection()
|
|
601
|
+
const job = { id: activationId, connection }
|
|
602
|
+
job.task = Promise.resolve(offerLocalRelayPairing(connection, force, activationId))
|
|
603
|
+
.catch(() => ({ ok: false }))
|
|
604
|
+
.then(result => {
|
|
605
|
+
if (!result?.ok && relayActivationSync === job) relayActivationSync = null
|
|
606
|
+
return result
|
|
607
|
+
})
|
|
608
|
+
relayActivationSync = job
|
|
609
|
+
return job.task
|
|
610
|
+
}
|
|
516
611
|
function apiUrl(path) {
|
|
517
612
|
return (state.server || '') + path
|
|
518
613
|
}
|
|
@@ -544,7 +639,7 @@ async function getWsTicket() {
|
|
|
544
639
|
const data = await (globalThis.DshNetwork?.readWithDeadline
|
|
545
640
|
? globalThis.DshNetwork.readWithDeadline(read,8000)
|
|
546
641
|
: read(AbortSignal.timeout(8000)))
|
|
547
|
-
if (!connection.valid()) throw new Error('stale ws ticket')
|
|
642
|
+
if (wsTicketPromise !== job || !connection.valid()) throw new Error('stale ws ticket')
|
|
548
643
|
if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
|
|
549
644
|
state.wsTicket = { token, server, value: data.ticket, expiresAt: Number(data.expiresAt) }
|
|
550
645
|
return data.ticket
|
|
@@ -592,13 +687,13 @@ async function rpc(method, payload = {}, timeoutMs = 45000, cancellation = null)
|
|
|
592
687
|
else if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
|
|
593
688
|
opts.signal = AbortSignal.timeout(timeoutMs)
|
|
594
689
|
}
|
|
595
|
-
const operation = window.DshOperations?.supports(method) && activeGatewayCapability('operations') === true
|
|
690
|
+
const operation = window.DshOperations?.supports(method) && (window.DshOperations.requiresReceipt?.(method) || activeGatewayCapability('operations') === true)
|
|
596
691
|
const connection = operation ? captureConnection() : null
|
|
597
692
|
const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
|
|
598
693
|
const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
|
|
599
694
|
diagnostic?.end({phase:'response',httpStatus:res.status})
|
|
600
695
|
if (res.status === 401) throw new Error('AUTH')
|
|
601
|
-
if (!res.ok)
|
|
696
|
+
if (!res.ok) { const error = new Error('HTTP ' + res.status); error.status = res.status; throw error }
|
|
602
697
|
const full = await res.json()
|
|
603
698
|
if (!full?.result) throw new Error(t('err.badResponse'))
|
|
604
699
|
if (!full.result.ok) {
|
|
@@ -642,11 +737,20 @@ function notifyPendingOperation(error, connection) {
|
|
|
642
737
|
}
|
|
643
738
|
async function safeRpc(method, payload, errText) {
|
|
644
739
|
const connection = captureConnection()
|
|
645
|
-
try {
|
|
740
|
+
try {
|
|
741
|
+
const value = await rpc(method, payload)
|
|
742
|
+
if (!connection.valid()) return null
|
|
743
|
+
if (method === 'session.list' && activeConnectionIssue()) {
|
|
744
|
+
connectionIssue = null
|
|
745
|
+
updateConn()
|
|
746
|
+
}
|
|
747
|
+
return value
|
|
748
|
+
}
|
|
646
749
|
catch (e) {
|
|
647
750
|
if (e.operationPending) { notifyPendingOperation(e, connection); return null }
|
|
648
751
|
if (!connection.valid()) return null
|
|
649
752
|
if (e.message === 'AUTH') authFailure()
|
|
753
|
+
else if (e.status === 426) authFailure(426)
|
|
650
754
|
else toast(errText ? `${errText}:${e.message}` : e.message, 'err')
|
|
651
755
|
return null
|
|
652
756
|
}
|
|
@@ -714,10 +818,18 @@ async function refreshHostDescription({ notify = false } = {}) {
|
|
|
714
818
|
return job
|
|
715
819
|
}
|
|
716
820
|
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
821
|
+
let connectionIssue = null
|
|
822
|
+
|
|
823
|
+
function activeConnectionIssue() {
|
|
824
|
+
return connectionIssue?.connection.valid() ? connectionIssue.status : null
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
function authFailure(status = 401) {
|
|
828
|
+
const previous = activeConnectionIssue()
|
|
829
|
+
if (previous === status) return
|
|
830
|
+
connectionIssue = { connection: captureConnection(), status }
|
|
831
|
+
updateConn()
|
|
832
|
+
if (!previous) toast(t(status === 426 ? 'conn.pairingNotice' : 'conn.authNotice'), 'err')
|
|
721
833
|
}
|
|
722
834
|
|
|
723
835
|
/* ---------------- 多服务器分组管理 + 自动选优 ---------------- */
|
|
@@ -749,6 +861,24 @@ function serverKey(server) {
|
|
|
749
861
|
return serverIdentity(server?.url ?? server, server?.token)
|
|
750
862
|
}
|
|
751
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
|
+
}
|
|
752
882
|
function currentServerEntry() {
|
|
753
883
|
return state.servers.find(s => s.url === state.server && serverToken(s) === state.token)
|
|
754
884
|
|| state.servers.find(s => s.url === state.server)
|
|
@@ -758,7 +888,8 @@ function setCurrentAccessToken(value) {
|
|
|
758
888
|
const token = normalizedServerToken(value)
|
|
759
889
|
if (!token) return false
|
|
760
890
|
const current = currentServerEntry()
|
|
761
|
-
|
|
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)
|
|
762
893
|
state.token = token
|
|
763
894
|
LS.set('token', token)
|
|
764
895
|
saveServers()
|
|
@@ -801,7 +932,8 @@ function loadServers() {
|
|
|
801
932
|
}
|
|
802
933
|
const legacyToken = normalizedServerToken(state.token || LS.get('token', ''))
|
|
803
934
|
state.servers = data.servers.filter(s => s && typeof s.url === 'string')
|
|
804
|
-
.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 } : {}) }))
|
|
805
937
|
state.groups = Array.isArray(data.groups) && data.groups.length ? data.groups : ['默认']
|
|
806
938
|
state.activeGroup = state.groups.includes(data.activeGroup) ? data.activeGroup : '默认'
|
|
807
939
|
state.autoSelect = data.autoSelect || {}
|
|
@@ -840,35 +972,25 @@ function serverCandidates() {
|
|
|
840
972
|
return list
|
|
841
973
|
}
|
|
842
974
|
|
|
843
|
-
|
|
975
|
+
function pingServer(base, token) {
|
|
844
976
|
const u = String(base || '').replace(/\/+$/, '')
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
const timer = setTimeout(() => ctrl.abort(), 3500)
|
|
849
|
-
try {
|
|
850
|
-
const res = await fetch(u + '/health?probe=live&t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
|
|
851
|
-
if (!res.ok) return Infinity
|
|
852
|
-
const health = await res.json().catch(() => null)
|
|
853
|
-
if (health && typeof health === 'object') {
|
|
977
|
+
return DshNetwork.probeGateway(u, {
|
|
978
|
+
headers: token === undefined ? undefined : { authorization: token ? 'Bearer ' + token : '', 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
|
|
979
|
+
onHealth: health => {
|
|
854
980
|
state.gatewayHealth[u] = health
|
|
855
981
|
renderOverview()
|
|
856
|
-
}
|
|
857
|
-
|
|
858
|
-
} catch {
|
|
859
|
-
return Infinity
|
|
860
|
-
} finally {
|
|
861
|
-
clearTimeout(timer)
|
|
862
|
-
}
|
|
982
|
+
},
|
|
983
|
+
})
|
|
863
984
|
}
|
|
864
985
|
|
|
865
986
|
function activeGatewayCapability(name) {
|
|
866
|
-
const capabilities = activeGatewayHealth()?.capabilities
|
|
987
|
+
const capabilities = activeGatewayHealth({ allowStale: true })?.capabilities
|
|
867
988
|
if (!capabilities || !Object.prototype.hasOwnProperty.call(capabilities, name)) return null
|
|
868
989
|
return Number(capabilities[name]) > 0
|
|
869
990
|
}
|
|
870
991
|
|
|
871
|
-
function activeGatewayHealth() {
|
|
992
|
+
function activeGatewayHealth({ allowStale = false } = {}) {
|
|
993
|
+
if (!allowStale && currentConnectionHealth() === null) return null
|
|
872
994
|
const key = String(state.server || location.origin || '').replace(/\/+$/, '')
|
|
873
995
|
return state.gatewayHealth[key] || null
|
|
874
996
|
}
|
|
@@ -880,6 +1002,45 @@ function dshReachable() {
|
|
|
880
1002
|
return !!state.hostInfo && state.hostInfo.metadataOnly !== true
|
|
881
1003
|
}
|
|
882
1004
|
|
|
1005
|
+
let connectionHealthProbe = null
|
|
1006
|
+
function currentConnectionHealth() {
|
|
1007
|
+
return connectionHealthProbe?.connection.valid() ? connectionHealthProbe.health : undefined
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
async function refreshConnectionHealth() {
|
|
1011
|
+
if (!state.token || navigator.onLine === false) return null
|
|
1012
|
+
const current = connectionHealthProbe?.connection.valid() ? connectionHealthProbe : null
|
|
1013
|
+
if (current?.task) return current.task
|
|
1014
|
+
const connection = captureConnection()
|
|
1015
|
+
const base = String(connection.server || location.origin).replace(/\/+$/, '')
|
|
1016
|
+
const probe = { connection, health: current?.health, task: null }
|
|
1017
|
+
connectionHealthProbe = probe
|
|
1018
|
+
const read = async (url, signal) => {
|
|
1019
|
+
try {
|
|
1020
|
+
const response = await fetch(url, { cache: 'no-store', signal })
|
|
1021
|
+
const value = response.ok ? await response.json() : null
|
|
1022
|
+
return value?.ok === true ? value : null
|
|
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
|
+
}
|
|
1033
|
+
if (probe !== connectionHealthProbe || !connection.valid()) return null
|
|
1034
|
+
probe.health = health
|
|
1035
|
+
// Failed probes do not invalidate advertised capabilities such as message receipts.
|
|
1036
|
+
if (health) state.gatewayHealth[base] = health
|
|
1037
|
+
probe.task = null
|
|
1038
|
+
updateConn()
|
|
1039
|
+
return health
|
|
1040
|
+
})()
|
|
1041
|
+
return probe.task
|
|
1042
|
+
}
|
|
1043
|
+
|
|
883
1044
|
async function selectFastestServer({ silent = false, reconnect = true } = {}) {
|
|
884
1045
|
const request = selectFastestServer.request = (selectFastestServer.request || 0) + 1
|
|
885
1046
|
const connection = captureConnection(), group = state.activeGroup
|
|
@@ -895,7 +1056,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
|
|
|
895
1056
|
let ms = Infinity
|
|
896
1057
|
|
|
897
1058
|
if (state.autoSelect[state.activeGroup] !== false) {
|
|
898
|
-
const measured = await Promise.all(candidates.map(async
|
|
1059
|
+
const measured = await Promise.all(candidates.map(async server => [server, await pingServer(server.url, server.token)]))
|
|
899
1060
|
if (!valid()) return null
|
|
900
1061
|
for (const [server, latency] of measured) state.serverLatency[serverKey(server)] = latency
|
|
901
1062
|
best = candidates
|
|
@@ -984,20 +1145,51 @@ function closeGroupMenu() {
|
|
|
984
1145
|
}
|
|
985
1146
|
|
|
986
1147
|
let groupDrawerReturnFocus = null
|
|
1148
|
+
let groupDrawerRoute = null
|
|
987
1149
|
|
|
988
1150
|
function groupDrawerOpen() {
|
|
989
|
-
return
|
|
1151
|
+
return $('group-drawer')?.classList.contains('hidden') === false
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
async function updateGroupDrawerRoute() {
|
|
1155
|
+
const status = $('group-drawer-connection')
|
|
1156
|
+
if (!status || !groupDrawerOpen()) return
|
|
1157
|
+
if (groupDrawerRoute?.connection.valid()) {
|
|
1158
|
+
status.textContent = t('groups.drawerRoute.' + groupDrawerRoute.category)
|
|
1159
|
+
return
|
|
1160
|
+
}
|
|
1161
|
+
const connection = captureConnection()
|
|
1162
|
+
const base = updateBase()
|
|
1163
|
+
const route = { connection, category: connection.token && base ? 'checking' : 'disconnected' }
|
|
1164
|
+
groupDrawerRoute = route
|
|
1165
|
+
status.textContent = t('groups.drawerRoute.' + route.category)
|
|
1166
|
+
if (route.category === 'disconnected') return
|
|
1167
|
+
|
|
1168
|
+
try {
|
|
1169
|
+
const response = await fetch(adminApiUrl('/admin/api/relay'), {
|
|
1170
|
+
headers: { authorization: 'Bearer ' + connection.token },
|
|
1171
|
+
cache: 'no-store',
|
|
1172
|
+
redirect: 'error',
|
|
1173
|
+
signal: AbortSignal.timeout(5000),
|
|
1174
|
+
})
|
|
1175
|
+
const data = response.ok ? await response.json() : null
|
|
1176
|
+
route.category = window.DshRelaySettings?.connectionCategory?.(data, base) || 'unknown'
|
|
1177
|
+
} catch {
|
|
1178
|
+
route.category = 'unknown'
|
|
1179
|
+
}
|
|
1180
|
+
if (groupDrawerRoute === route && connection.valid()) {
|
|
1181
|
+
status.textContent = t('groups.drawerRoute.' + route.category)
|
|
1182
|
+
}
|
|
990
1183
|
}
|
|
991
1184
|
|
|
992
1185
|
function renderGroupDrawer() {
|
|
993
1186
|
const trigger = $('group-drawer-trigger')
|
|
994
1187
|
const brandGroup = $('brand-group-name')
|
|
995
|
-
const current = $('group-drawer-current')
|
|
996
1188
|
const list = $('group-drawer-list')
|
|
997
1189
|
if (brandGroup) brandGroup.textContent = state.activeGroup
|
|
998
|
-
if (trigger) trigger.setAttribute('aria-label', t('groups.
|
|
999
|
-
if (
|
|
1000
|
-
|
|
1190
|
+
if (trigger) trigger.setAttribute('aria-label', t('groups.drawerOpenFor', { group: state.activeGroup }))
|
|
1191
|
+
if (!list || $('group-drawer-groups-panel').hidden || !groupDrawerOpen()) return
|
|
1192
|
+
void updateGroupDrawerRoute()
|
|
1001
1193
|
list.innerHTML = state.groups.map(group => {
|
|
1002
1194
|
const servers = groupServers(group)
|
|
1003
1195
|
const selected = group === state.activeGroup
|
|
@@ -1009,18 +1201,253 @@ function renderGroupDrawer() {
|
|
|
1009
1201
|
}).join('')
|
|
1010
1202
|
}
|
|
1011
1203
|
|
|
1204
|
+
function renderGroupDrawerSessions() {
|
|
1205
|
+
const list = $('group-drawer-sessions')
|
|
1206
|
+
if (!list || $('group-drawer-recent').hidden || !groupDrawerOpen()) return
|
|
1207
|
+
const archived = new Set(state.wbArchived || [])
|
|
1208
|
+
const sessions = state.sessions.filter(session => isVisibleSession(session) && !archived.has(session.sessionId))
|
|
1209
|
+
.sort((a, b) => sessionSortTime(b) - sessionSortTime(a)).slice(0, 5)
|
|
1210
|
+
$('group-drawer-recent-empty').hidden = sessions.length > 0
|
|
1211
|
+
const rows = sessions.map(session => {
|
|
1212
|
+
const id = session.sessionId
|
|
1213
|
+
const title = esc(sessionLabelOf(session))
|
|
1214
|
+
const current = id === state.current && !$('view-session').classList.contains('hidden')
|
|
1215
|
+
return `<button type="button" class="group-drawer-session${current ? ' current' : ''}" data-drawer-session="${esc(id)}"${current ? ' aria-current="true"' : ''}>
|
|
1216
|
+
<span class="group-drawer-session-title" title="${title}">${title}</span>
|
|
1217
|
+
<span class="group-drawer-session-meta">${esc(sessionWorkspaceName(session))}</span>
|
|
1218
|
+
</button>`
|
|
1219
|
+
}).join('')
|
|
1220
|
+
if (list.innerHTML === rows) return
|
|
1221
|
+
const focusedId = list.contains(document.activeElement) ? document.activeElement.dataset.drawerSession : null
|
|
1222
|
+
list.innerHTML = rows
|
|
1223
|
+
if (focusedId) {
|
|
1224
|
+
const focus = [...list.children].find(row => row.dataset.drawerSession === focusedId) || $('group-drawer-panel-title')
|
|
1225
|
+
focus.focus({ preventScroll: true })
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
const GROUP_DRAWER_SHORTCUT_PREFS = 'groupDrawerHiddenShortcutsV1'
|
|
1230
|
+
|
|
1231
|
+
function readGroupDrawerHiddenShortcuts() {
|
|
1232
|
+
const stored = cacheRead(GROUP_DRAWER_SHORTCUT_PREFS)
|
|
1233
|
+
return new Set(Array.isArray(stored) ? stored.filter(key => typeof key === 'string') : [])
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
function applyGroupDrawerShortcuts(hidden) {
|
|
1237
|
+
for (const shortcut of $('group-drawer').querySelectorAll('[data-drawer-shortcut]')) {
|
|
1238
|
+
shortcut.hidden = hidden.has(shortcut.dataset.drawerShortcut)
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
function saveGroupDrawerShortcuts(hidden) {
|
|
1243
|
+
if (!LS.set(GROUP_DRAWER_SHORTCUT_PREFS, JSON.stringify([...hidden]))) {
|
|
1244
|
+
toast(t('groups.drawerSaveFailed'), 'err')
|
|
1245
|
+
return false
|
|
1246
|
+
}
|
|
1247
|
+
applyGroupDrawerShortcuts(hidden)
|
|
1248
|
+
return true
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
function renderGroupDrawerEditor() {
|
|
1252
|
+
const options = $('group-drawer-shortcut-options')
|
|
1253
|
+
const rows = [...$('group-drawer').querySelectorAll('[data-drawer-shortcut]')].map(shortcut => {
|
|
1254
|
+
const row = document.createElement('label')
|
|
1255
|
+
const name = document.createElement('span')
|
|
1256
|
+
const checkbox = document.createElement('input')
|
|
1257
|
+
row.className = 'group-drawer-toggle'
|
|
1258
|
+
name.textContent = t(shortcut.dataset.i18nAria)
|
|
1259
|
+
checkbox.type = 'checkbox'
|
|
1260
|
+
checkbox.checked = !shortcut.hidden
|
|
1261
|
+
checkbox.dataset.drawerShortcutSetting = shortcut.dataset.drawerShortcut
|
|
1262
|
+
row.append(shortcut.querySelector('svg').cloneNode(true), name, checkbox)
|
|
1263
|
+
return row
|
|
1264
|
+
})
|
|
1265
|
+
options.replaceChildren(...rows)
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
const GROUP_DRAWER_PREVIEW_LIMIT = 6
|
|
1269
|
+
let groupDrawerPreviewRead = null
|
|
1270
|
+
|
|
1271
|
+
function isGroupDrawerPanel(name) {
|
|
1272
|
+
return groupDrawerOpen() && $('group-drawer').dataset.panel === name
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
async function renderGroupDrawerNewSession() {
|
|
1276
|
+
const connection = captureConnection()
|
|
1277
|
+
const preview = new AbortController()
|
|
1278
|
+
groupDrawerPreviewRead = preview
|
|
1279
|
+
const current = () => isGroupDrawerPanel('new') && connection.valid() && groupDrawerPreviewRead === preview
|
|
1280
|
+
const form = $('group-drawer-new-form')
|
|
1281
|
+
const status = $('group-drawer-new-status')
|
|
1282
|
+
form.hidden = true
|
|
1283
|
+
status.hidden = false
|
|
1284
|
+
$('group-drawer-new-connect').hidden = !!connection.token
|
|
1285
|
+
status.textContent = t(connection.token ? 'session.loading' : 'groups.drawerConnectFirst')
|
|
1286
|
+
if (!connection.token) return
|
|
1287
|
+
form.append($('new-session-card'))
|
|
1288
|
+
try {
|
|
1289
|
+
if (!await prepareNewSessionForm('', current)) return
|
|
1290
|
+
status.hidden = true
|
|
1291
|
+
form.hidden = false
|
|
1292
|
+
} catch {
|
|
1293
|
+
if (current()) status.textContent = t('groups.drawerPreviewFailed')
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
function groupDrawerPreviewRow(title, meta, icon = '') {
|
|
1298
|
+
return `<div class="group-drawer-preview-row">${icon}<div class="group-drawer-option-copy">
|
|
1299
|
+
<span class="group-drawer-option-name" title="${esc(title)}">${esc(title)}</span>
|
|
1300
|
+
<span class="group-drawer-option-meta">${esc(meta)}</span>
|
|
1301
|
+
</div></div>`
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
async function readGroupDrawerPreview(name, url, headers, render) {
|
|
1305
|
+
const status = $('group-drawer-' + name + '-status')
|
|
1306
|
+
const list = $('group-drawer-' + name + '-list')
|
|
1307
|
+
const connection = captureConnection()
|
|
1308
|
+
list.replaceChildren()
|
|
1309
|
+
status.textContent = t(connection.token ? 'session.loading' : 'groups.drawerConnectFirst')
|
|
1310
|
+
if (!connection.token) return
|
|
1311
|
+
const controller = new AbortController()
|
|
1312
|
+
groupDrawerPreviewRead = controller
|
|
1313
|
+
const current = () => groupDrawerPreviewRead === controller && !controller.signal.aborted && connection.valid() && isGroupDrawerPanel(name)
|
|
1314
|
+
try {
|
|
1315
|
+
const response = await fetch(url, { headers, signal: AbortSignal.any([controller.signal, AbortSignal.timeout(15000)]) })
|
|
1316
|
+
if (!response.ok) throw Error('preview request failed')
|
|
1317
|
+
const data = await response.json()
|
|
1318
|
+
if (current()) render(data, list, status)
|
|
1319
|
+
} catch {
|
|
1320
|
+
if (current()) status.textContent = t('groups.drawerPreviewFailed')
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
function renderGroupDrawerFiles() {
|
|
1325
|
+
const path = $('group-drawer-files-path')
|
|
1326
|
+
path.hidden = true
|
|
1327
|
+
const workspace = workspaceById(state.fs.workspaceId)
|
|
1328
|
+
const target = (state.fs.loaded && state.fs.path) || workspace?.path || ''
|
|
1329
|
+
void readGroupDrawerPreview('files', fsApiUrl('/list', { path: target }), fsHeaders(), (data, list, status) => {
|
|
1330
|
+
if (!Array.isArray(data.entries)) throw Error('invalid file list')
|
|
1331
|
+
path.textContent = data.path || target
|
|
1332
|
+
path.hidden = !path.textContent
|
|
1333
|
+
status.textContent = t(data.entries.length ? 'groups.drawerFileCount' : 'fs.emptyDir', { n: data.entries.length })
|
|
1334
|
+
list.innerHTML = data.entries.slice(0, GROUP_DRAWER_PREVIEW_LIMIT).map(entry => {
|
|
1335
|
+
const isDir = entry.type === 'dir'
|
|
1336
|
+
return groupDrawerPreviewRow(entry.name, isDir ? t('fs.dir') : fmtSize(entry.size), fsIconSvg(isDir))
|
|
1337
|
+
}).join('')
|
|
1338
|
+
})
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
function renderGroupDrawerPlugins() {
|
|
1342
|
+
const config = optionalPluginConfig()
|
|
1343
|
+
void readGroupDrawerPreview('plugins', config.url('/remote/api/plugins/state'), config.headers, (data, list, status) => {
|
|
1344
|
+
if (data.ok !== true || !Array.isArray(data.items)) throw Error('invalid plugin state')
|
|
1345
|
+
const plugins = data.items.filter(item => item?.name).sort((a, b) => Number(!!b.enabled) - Number(!!a.enabled))
|
|
1346
|
+
status.textContent = t(plugins.length ? 'groups.drawerPluginCount' : 'groups.drawerNoPlugins', { n: plugins.length })
|
|
1347
|
+
list.innerHTML = plugins.slice(0, GROUP_DRAWER_PREVIEW_LIMIT).map(item => {
|
|
1348
|
+
const stateLabel = t(item.enabled ? 'groups.drawerPluginEnabled' : 'groups.drawerPluginDisabled')
|
|
1349
|
+
const meta = item.version ? item.version + ' · ' + stateLabel : stateLabel
|
|
1350
|
+
return groupDrawerPreviewRow(item.displayName || item.name, meta)
|
|
1351
|
+
}).join('')
|
|
1352
|
+
})
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
function renderGroupDrawerOperations() {
|
|
1356
|
+
if (!isGroupDrawerPanel('operations')) return
|
|
1357
|
+
const pending = [
|
|
1358
|
+
...state.approvals.map(item => ({ sessionId: item.sessionId, title: t('pending.approvalTitle', { tool: item.toolName || t('tool.default') }) })),
|
|
1359
|
+
...state.questions.map(item => ({ sessionId: item.sessionId, title: item.questions?.[0]?.question || t('notify.questionTitle') })),
|
|
1360
|
+
]
|
|
1361
|
+
const receipts = window.DshOperations?.pending().length || 0
|
|
1362
|
+
$('group-drawer-pending-summary').textContent = t(pending.length ? 'pending.count' : 'pending.empty', { n: pending.length })
|
|
1363
|
+
$('group-drawer-receipts-summary').textContent = t(receipts ? 'groups.drawerReceipts' : 'groups.drawerNoReceipts', { n: receipts })
|
|
1364
|
+
$('group-drawer-pending-list').innerHTML = pending.slice(0, GROUP_DRAWER_PREVIEW_LIMIT)
|
|
1365
|
+
.map(item => groupDrawerPreviewRow(item.title, titleOf(state.byId.get(item.sessionId)))).join('')
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
function renderGroupDrawerSettings() {
|
|
1369
|
+
const rows = [...$('settings-home').querySelectorAll('[data-settings-group], #btn-host-schedule')].filter(row => !row.hidden)
|
|
1370
|
+
$('group-drawer-settings-list').innerHTML = rows.map(row => {
|
|
1371
|
+
const target = row.dataset.settingsGroup
|
|
1372
|
+
const title = row.querySelector('.setting-name')?.textContent || row.textContent.trim()
|
|
1373
|
+
const description = row.querySelector('.setting-desc')?.textContent || ''
|
|
1374
|
+
return `<button type="button" class="group-drawer-preview-row" ${target ? `data-drawer-setting="${esc(target)}"` : 'data-drawer-view="view-schedule"'}>
|
|
1375
|
+
<span class="group-drawer-option-copy"><span class="group-drawer-option-name">${esc(title)}</span>
|
|
1376
|
+
${description ? `<span class="group-drawer-option-meta">${esc(description)}</span>` : ''}</span>
|
|
1377
|
+
<span aria-hidden="true">›</span></button>`
|
|
1378
|
+
}).join('')
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
function renderGroupDrawerVersion() {
|
|
1382
|
+
const version = activeGatewayHealth()?.version
|
|
1383
|
+
$('group-drawer-gateway-version').textContent = version ? 'v' + version : '—'
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
function setGroupDrawerPanel(name, moveFocus = true) {
|
|
1387
|
+
const drawer = $('group-drawer')
|
|
1388
|
+
const previous = drawer.dataset.panel || ''
|
|
1389
|
+
if (previous !== name) {
|
|
1390
|
+
groupDrawerPreviewRead?.abort()
|
|
1391
|
+
groupDrawerPreviewRead = null
|
|
1392
|
+
if (['new', 'search'].includes(previous) && customSelectCurrent?.select.closest('[data-drawer-panel]')?.dataset.drawerPanel === previous) {
|
|
1393
|
+
closeCustomSelect({ restoreFocus: false })
|
|
1394
|
+
}
|
|
1395
|
+
if (previous === 'new') $('modal-new-session').append($('new-session-card'))
|
|
1396
|
+
}
|
|
1397
|
+
let active
|
|
1398
|
+
let previousTrigger
|
|
1399
|
+
for (const button of drawer.querySelectorAll('[data-drawer-open-panel]')) {
|
|
1400
|
+
const key = button.dataset.drawerOpenPanel
|
|
1401
|
+
button.setAttribute('aria-expanded', String(key === name))
|
|
1402
|
+
if (key === name) active = button
|
|
1403
|
+
if (key === previous) previousTrigger = button
|
|
1404
|
+
}
|
|
1405
|
+
drawer.dataset.panel = active ? name : ''
|
|
1406
|
+
$('group-drawer-panel').hidden = !active
|
|
1407
|
+
for (const section of drawer.querySelectorAll('[data-drawer-panel]')) {
|
|
1408
|
+
section.hidden = section.dataset.drawerPanel !== drawer.dataset.panel
|
|
1409
|
+
}
|
|
1410
|
+
if (!active) {
|
|
1411
|
+
if (moveFocus) previousTrigger?.focus({ preventScroll: true })
|
|
1412
|
+
return
|
|
1413
|
+
}
|
|
1414
|
+
const title = $('group-drawer-panel-title')
|
|
1415
|
+
title.textContent = t(active.dataset.i18nAria)
|
|
1416
|
+
drawer.querySelector('.group-drawer-body').scrollTop = 0
|
|
1417
|
+
if (name === 'recent') renderGroupDrawerSessions()
|
|
1418
|
+
if (name === 'groups') renderGroupDrawer()
|
|
1419
|
+
if (name === 'edit') renderGroupDrawerEditor()
|
|
1420
|
+
if (name === 'search') refreshDrawerSearch()
|
|
1421
|
+
if (name === 'new') void renderGroupDrawerNewSession()
|
|
1422
|
+
if (name === 'files') renderGroupDrawerFiles()
|
|
1423
|
+
if (name === 'operations') renderGroupDrawerOperations()
|
|
1424
|
+
if (name === 'plugins') renderGroupDrawerPlugins()
|
|
1425
|
+
if (name === 'settings') renderGroupDrawerSettings()
|
|
1426
|
+
if (name === 'version') renderGroupDrawerVersion()
|
|
1427
|
+
if (moveFocus) title.focus({ preventScroll: true })
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
function backGroupDrawer() {
|
|
1431
|
+
if ($('group-drawer').dataset.panel) setGroupDrawerPanel('')
|
|
1432
|
+
else closeGroupDrawer()
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1012
1435
|
function openGroupDrawer() {
|
|
1013
1436
|
const drawer = $('group-drawer')
|
|
1014
1437
|
const backdrop = $('group-drawer-backdrop')
|
|
1015
1438
|
const trigger = $('group-drawer-trigger')
|
|
1016
1439
|
if (!drawer || !backdrop || !trigger) return
|
|
1017
|
-
|
|
1018
|
-
groupDrawerReturnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : trigger
|
|
1440
|
+
groupDrawerReturnFocus = document.activeElement === $('btn-session-more') ? document.activeElement : trigger
|
|
1019
1441
|
drawer.classList.remove('hidden')
|
|
1020
1442
|
backdrop.classList.remove('hidden')
|
|
1021
1443
|
document.body.classList.add('group-drawer-open')
|
|
1022
1444
|
trigger.setAttribute('aria-expanded', 'true')
|
|
1023
|
-
|
|
1445
|
+
applyGroupDrawerShortcuts(readGroupDrawerHiddenShortcuts())
|
|
1446
|
+
setGroupDrawerPanel('', false)
|
|
1447
|
+
drawer.querySelector('.group-drawer-icons').scrollTop = 0
|
|
1448
|
+
requestAnimationFrame(() => {
|
|
1449
|
+
if (groupDrawerOpen()) $('group-drawer-close')?.focus({ preventScroll: true })
|
|
1450
|
+
})
|
|
1024
1451
|
}
|
|
1025
1452
|
|
|
1026
1453
|
function closeGroupDrawer({ restoreFocus = true } = {}) {
|
|
@@ -1028,24 +1455,27 @@ function closeGroupDrawer({ restoreFocus = true } = {}) {
|
|
|
1028
1455
|
const backdrop = $('group-drawer-backdrop')
|
|
1029
1456
|
const trigger = $('group-drawer-trigger')
|
|
1030
1457
|
if (!drawer || !backdrop || drawer.classList.contains('hidden')) return
|
|
1458
|
+
setGroupDrawerPanel('', false)
|
|
1031
1459
|
drawer.classList.add('hidden')
|
|
1032
1460
|
backdrop.classList.add('hidden')
|
|
1033
1461
|
document.body.classList.remove('group-drawer-open')
|
|
1034
1462
|
trigger?.setAttribute('aria-expanded', 'false')
|
|
1035
1463
|
if (restoreFocus) (groupDrawerReturnFocus || trigger)?.focus({ preventScroll: true })
|
|
1036
1464
|
groupDrawerReturnFocus = null
|
|
1465
|
+
groupDrawerRoute = null
|
|
1037
1466
|
}
|
|
1038
1467
|
|
|
1039
1468
|
function keepGroupDrawerFocus(event) {
|
|
1040
|
-
if (!groupDrawerOpen()) return
|
|
1469
|
+
if (!groupDrawerOpen() || customSelectCurrent) return
|
|
1041
1470
|
if (event.key === 'Escape') {
|
|
1042
1471
|
event.preventDefault()
|
|
1043
|
-
|
|
1472
|
+
backGroupDrawer()
|
|
1044
1473
|
return
|
|
1045
1474
|
}
|
|
1046
1475
|
if (event.key !== 'Tab') return
|
|
1047
1476
|
const drawer = $('group-drawer')
|
|
1048
|
-
const targets = [...drawer.querySelectorAll('button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])')]
|
|
1477
|
+
const targets = [...drawer.querySelectorAll('button:not([disabled]), input:not([disabled]), [href], [tabindex]:not([tabindex="-1"])')]
|
|
1478
|
+
.filter(element => element.getClientRects().length)
|
|
1049
1479
|
if (!targets.length) return
|
|
1050
1480
|
const first = targets[0]
|
|
1051
1481
|
const last = targets[targets.length - 1]
|
|
@@ -1062,9 +1492,12 @@ function renderServers() {
|
|
|
1062
1492
|
const list = groupServers(g)
|
|
1063
1493
|
const auto = state.autoSelect[g] !== false
|
|
1064
1494
|
const activeManual = state.groupActive[g] || ''
|
|
1495
|
+
const tokens = new Set(list.map(serverToken).filter(Boolean))
|
|
1496
|
+
const mixedToken = tokens.size > 1
|
|
1065
1497
|
return `<div class="srv-group" data-group="${esc(g)}">
|
|
1066
1498
|
<div class="srv-group-head">
|
|
1067
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>` : ''}
|
|
1068
1501
|
<button class="srv-group-speed mini-btn" data-speed-group="${esc(g)}" title="${t('groups.speedTest')}">⚡</button>
|
|
1069
1502
|
<label class="switch small" title="${t('groups.autoSelect')}">
|
|
1070
1503
|
<input type="checkbox" data-auto-group="${esc(g)}" ${auto ? 'checked' : ''}>
|
|
@@ -1103,6 +1536,20 @@ function renderServers() {
|
|
|
1103
1536
|
b.addEventListener('dblclick', () => renameGroup(b.dataset.groupName))
|
|
1104
1537
|
})
|
|
1105
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
|
+
}))
|
|
1106
1553
|
box.querySelectorAll('[data-auto-group]').forEach(chk => chk.addEventListener('change', (e) => {
|
|
1107
1554
|
const g = e.target.dataset.autoGroup
|
|
1108
1555
|
state.autoSelect[g] = e.target.checked
|
|
@@ -1158,10 +1605,17 @@ async function addServer() {
|
|
|
1158
1605
|
} catch {
|
|
1159
1606
|
return toast(t('servers.badProtocol'), 'err')
|
|
1160
1607
|
}
|
|
1161
|
-
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)
|
|
1162
1616
|
if (state.servers.some(s => serverIdentity(s.url, serverToken(s)) === serverIdentity(raw, token))) return toast(t('servers.duplicate'))
|
|
1163
1617
|
let note = prompt(t('servers.promptNote'), '') || ''
|
|
1164
|
-
state.servers.push({ id: newServerId(), url: raw, note: note.trim(), group
|
|
1618
|
+
state.servers.push({ id: newServerId(), url: raw, note: note.trim(), group, token })
|
|
1165
1619
|
saveServers()
|
|
1166
1620
|
if (input) input.value = ''
|
|
1167
1621
|
renderServers()
|
|
@@ -1190,10 +1644,17 @@ function editServer(id) {
|
|
|
1190
1644
|
if (group === null) return
|
|
1191
1645
|
const wasActive = state.server === s.url && state.token === serverToken(s)
|
|
1192
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
|
+
}
|
|
1193
1652
|
s.url = raw
|
|
1194
1653
|
s.note = note.trim()
|
|
1195
1654
|
s.group = ensureGroup(group.trim() || '默认')
|
|
1196
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)
|
|
1197
1658
|
if (wasActive) {
|
|
1198
1659
|
if (changedActiveUrl) resetFsForServer()
|
|
1199
1660
|
state.server = raw
|
|
@@ -1209,8 +1670,16 @@ function editServer(id) {
|
|
|
1209
1670
|
function removeServer(id) {
|
|
1210
1671
|
const s = state.servers.find(x => x.id === id)
|
|
1211
1672
|
if (!s) return
|
|
1212
|
-
|
|
1213
|
-
|
|
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
|
+
}
|
|
1214
1683
|
state.servers = state.servers.filter(x => x.id !== id)
|
|
1215
1684
|
const wasActive = state.server === s.url && state.token === serverToken(s)
|
|
1216
1685
|
// 清理该组手动指定
|
|
@@ -1325,6 +1794,7 @@ function closeStream(kind) {
|
|
|
1325
1794
|
const ws = streams[kind]
|
|
1326
1795
|
streams[kind] = null
|
|
1327
1796
|
state.streamsOk[kind] = false
|
|
1797
|
+
ws?._continuity?.finish(true)
|
|
1328
1798
|
try { ws?.close() } catch {}
|
|
1329
1799
|
}
|
|
1330
1800
|
|
|
@@ -1357,7 +1827,8 @@ function clearReconnect() {
|
|
|
1357
1827
|
|
|
1358
1828
|
function openStreams() {
|
|
1359
1829
|
if (!state.token) return
|
|
1360
|
-
|
|
1830
|
+
void refreshConnectionHealth()
|
|
1831
|
+
if (state.streamMode === 'poll' && !pollTimer && navigator.onLine) startPolling()
|
|
1361
1832
|
openStream('mux', onMuxFrame, true)
|
|
1362
1833
|
openStream('host', onHostFrame, false)
|
|
1363
1834
|
}
|
|
@@ -1397,8 +1868,9 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1397
1868
|
const clientMark = CAP?.isNativePlatform?.() ? 'app' : 'web'
|
|
1398
1869
|
const auth = ticket ? `ticket=${encodeURIComponent(ticket)}` : `token=${encodeURIComponent(state.token)}`
|
|
1399
1870
|
const clientId = CLIENT_ID ? `&clientId=${encodeURIComponent(CLIENT_ID)}` : ''
|
|
1400
|
-
const streamUrl = `${base}/api/events.${kind}?${auth}&client=${clientMark}${clientId}`
|
|
1401
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 : ''}`
|
|
1402
1874
|
if (current?._streamUrl === streamUrl &&
|
|
1403
1875
|
(current.readyState === WebSocket.OPEN || current.readyState === WebSocket.CONNECTING)) return
|
|
1404
1876
|
if (current && current._streamUrl !== streamUrl) {
|
|
@@ -1412,6 +1884,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1412
1884
|
const ws = new WebSocket(streamUrl)
|
|
1413
1885
|
streams[kind] = ws
|
|
1414
1886
|
ws._streamUrl = streamUrl
|
|
1887
|
+
ws._continuityId = streamId
|
|
1415
1888
|
ws._generation = generation
|
|
1416
1889
|
ws._isRestore = !!isRestore
|
|
1417
1890
|
ws.onopen = () => {
|
|
@@ -1451,6 +1924,10 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1451
1924
|
updateConn()
|
|
1452
1925
|
try {
|
|
1453
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
|
+
}
|
|
1454
1931
|
handler(full)
|
|
1455
1932
|
} catch {}
|
|
1456
1933
|
}
|
|
@@ -1507,6 +1984,7 @@ function enterPollMode() {
|
|
|
1507
1984
|
function stopPolling() {
|
|
1508
1985
|
pollInFlight?.stop()
|
|
1509
1986
|
pollInFlight = null
|
|
1987
|
+
delete state.pollSeq.muxReady
|
|
1510
1988
|
clearInterval(pollTimer); pollTimer = null
|
|
1511
1989
|
clearInterval(wsRetryTimer); wsRetryTimer = null
|
|
1512
1990
|
}
|
|
@@ -1548,12 +2026,15 @@ async function pollKind(kind, cancellation) {
|
|
|
1548
2026
|
result=await read(signal)
|
|
1549
2027
|
}
|
|
1550
2028
|
res=result.res;data=result.data
|
|
1551
|
-
} catch {
|
|
1552
|
-
if (!valid()) return
|
|
1553
|
-
if (res.status === 401) { authFailure(); return }
|
|
1554
|
-
if (!res.ok) return
|
|
2029
|
+
} catch {}
|
|
1555
2030
|
if (!valid()) return
|
|
1556
|
-
|
|
2031
|
+
const received = !!res?.ok && Array.isArray(data?.events)
|
|
2032
|
+
if (kind === 'mux' && !!cursors.muxReady !== received) {
|
|
2033
|
+
cursors.muxReady = received
|
|
2034
|
+
updateConn()
|
|
2035
|
+
}
|
|
2036
|
+
if (res?.status === 401) { authFailure(); return }
|
|
2037
|
+
if (!received) return
|
|
1557
2038
|
// 网关重启或客户端离线过久后,游标可能落后于内存环形缓冲;
|
|
1558
2039
|
// 从当前缓冲重新接收,并刷新权威会话列表,避免静默漏事件。
|
|
1559
2040
|
const reset = data.reset === true || (!!data.epoch && !!cursors[kind + 'Epoch'] && cursors[kind + 'Epoch'] !== data.epoch) || data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
|
|
@@ -1596,9 +2077,66 @@ function tryRestoreWs() {
|
|
|
1596
2077
|
if (!streams.host && !streamMeta.host.retryTimer) openStream('host', onHostFrame, false, true)
|
|
1597
2078
|
}
|
|
1598
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
|
+
|
|
1599
2136
|
/* 回前台恢复: 强制重排修复 MIUI WebView 后台切回时 sticky 顶栏不绘制的问题 */
|
|
1600
2137
|
function onResume() {
|
|
1601
2138
|
if (document.visibilityState !== 'visible') return
|
|
2139
|
+
resetRealtimeAfterBackground()
|
|
1602
2140
|
applyNativeInsets()
|
|
1603
2141
|
// 视图状态与 body class 兜底同步(会话页顶栏按设计隐藏, 主页必须恢复显示)
|
|
1604
2142
|
document.body.classList.toggle('in-session', !$('view-session').classList.contains('hidden'))
|
|
@@ -1612,7 +2150,7 @@ function onResume() {
|
|
|
1612
2150
|
updateConn()
|
|
1613
2151
|
void openPendingNavigation()
|
|
1614
2152
|
recoverSessionHistory()
|
|
1615
|
-
if(state.token)openStreams()
|
|
2153
|
+
if (state.token && navigator.onLine) openStreams()
|
|
1616
2154
|
}
|
|
1617
2155
|
|
|
1618
2156
|
/* 回前台 / 定时兜底: 任何流不在 OPEN 就重连; 多服务器时顺便重测速 */
|
|
@@ -1622,11 +2160,12 @@ document.addEventListener('visibilitychange', () => {
|
|
|
1622
2160
|
if (window.NativeBackground?.getPendingNavigation?.()) return
|
|
1623
2161
|
if (state.servers.length) selectFastestServer({ silent: true })
|
|
1624
2162
|
else if (state.token) repairMissingStreams()
|
|
1625
|
-
}
|
|
2163
|
+
} else markRealtimeBackgrounded()
|
|
1626
2164
|
})
|
|
1627
2165
|
window.addEventListener('pageshow', onResume)
|
|
1628
2166
|
setInterval(() => {
|
|
1629
|
-
if (document.visibilityState === 'visible' && state.token) {
|
|
2167
|
+
if (document.visibilityState === 'visible' && state.token && navigator.onLine) {
|
|
2168
|
+
void refreshConnectionHealth()
|
|
1630
2169
|
repairMissingStreams()
|
|
1631
2170
|
sessionSyncTick()
|
|
1632
2171
|
}
|
|
@@ -1638,6 +2177,7 @@ setInterval(() => {
|
|
|
1638
2177
|
|
|
1639
2178
|
/* 网络感知: 离线立刻关 WS + 显示离线, 在线立即重连 */
|
|
1640
2179
|
window.addEventListener('offline', () => {
|
|
2180
|
+
connectionHealthProbe = null
|
|
1641
2181
|
clearReconnect()
|
|
1642
2182
|
closeStream('mux')
|
|
1643
2183
|
closeStream('host')
|
|
@@ -1664,6 +2204,7 @@ navigator.connection?.addEventListener?.('change',()=>{
|
|
|
1664
2204
|
function onMuxFrame(full) {
|
|
1665
2205
|
const f = full.payload
|
|
1666
2206
|
if (!f) return
|
|
2207
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.handleFrame?.(full)
|
|
1667
2208
|
if (f.type === 'session/reasoning') {
|
|
1668
2209
|
if (f.sessionId === state.current) { applyReasoningBaseline(f.partialReasoning); scheduleReasoningRender() }
|
|
1669
2210
|
return
|
|
@@ -1682,24 +2223,40 @@ function onMuxFrame(full) {
|
|
|
1682
2223
|
state.questions = state.questions.filter(q => q.rpcId !== full.rpcId)
|
|
1683
2224
|
state.questions.push({ ...f, rpcId: full.rpcId })
|
|
1684
2225
|
notifyPendingRequest(full, t('notify.questionTitle'), f.questions?.map(q => q.question).join(' / ') || t('notify.questionBody'))
|
|
1685
|
-
renderPending(); return
|
|
2226
|
+
renderPending(); if (typeof refreshPlanReview === 'function') refreshPlanReview(); return
|
|
1686
2227
|
}
|
|
1687
2228
|
if (f.type === 'question/resolved') {
|
|
1688
2229
|
clearPendingNotification(f)
|
|
1689
2230
|
state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId)
|
|
1690
2231
|
if (state.questionModal?.rpcId === f.questionRpcId) { $('modal-question').classList.add('hidden'); state.questionModal = null }
|
|
1691
|
-
renderPending(); return
|
|
2232
|
+
renderPending(); if (typeof refreshPlanReview === 'function') refreshPlanReview(); return
|
|
2233
|
+
}
|
|
2234
|
+
if (f.type === 'session/queue') {
|
|
2235
|
+
if (hostQueue?.accept(f.sessionId, f.seq) !== false) state.queues[f.sessionId] = f.items || []
|
|
2236
|
+
renderQueue(); return
|
|
1692
2237
|
}
|
|
1693
|
-
if (f.type === 'session/queue') { state.queues[f.sessionId] = f.items || []; renderQueue(); return }
|
|
1694
2238
|
if (f.type === 'session/jobs') { state.jobs[f.sessionId] = f.jobs || []; renderJobs(); return }
|
|
1695
|
-
if (f.type === 'session/projection') {
|
|
2239
|
+
if (f.type === 'session/projection') {
|
|
2240
|
+
applyProjection(f.sessionId, f.key, f.value, f.seq)
|
|
2241
|
+
if (f.key === 'plan' && f.sessionId === state.current && typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
2242
|
+
if (f.key === 'conversationContinuation' && f.sessionId === state.current) renderHistory()
|
|
2243
|
+
if (f.key === 'agentTeam') window.DshSubagents?.updateTeam?.(f.sessionId, f.value, f.seq)
|
|
2244
|
+
return
|
|
2245
|
+
}
|
|
1696
2246
|
if (f.type === 'stream/error') { toast(t('stream.error', { msg: f.error?.message || '' }), 'err') }
|
|
1697
2247
|
if (f.type === 'session/stream-error' && f.sessionId === state.current) { setSessionRecovery('error', f.error?.code === 'session/migration-required' ? t('session.migrationRequired') : f.error?.message); toast(f.error?.code === 'session/migration-required' ? t('session.migrationRequired') : f.error?.message, 'err') }
|
|
1698
2248
|
}
|
|
1699
2249
|
function onHostFrame(full) {
|
|
1700
2250
|
const f = full.payload
|
|
1701
2251
|
if (!f) return
|
|
2252
|
+
if (f.type === 'host/relay-activation') { void syncRelayActivation(f.activationId); return }
|
|
2253
|
+
if (f.type === 'schedule/changed') { void hostSchedule?.refresh(true); return }
|
|
1702
2254
|
if (['host/session-status', 'host/agent-error'].includes(f.type) && typeof window !== 'undefined' && window.NativeBackground?.handleTaskEvent) window.NativeBackground.handleTaskEvent(bgBase(), state.token || '', JSON.stringify(full), f.replay === true)
|
|
2255
|
+
if (f.type === 'host/pinned-sessions-changed') {
|
|
2256
|
+
state.wbPinned = Array.isArray(f.pinnedSessionIds) ? f.pinnedSessionIds : []
|
|
2257
|
+
renderSessions()
|
|
2258
|
+
return
|
|
2259
|
+
}
|
|
1703
2260
|
if (['host/session-added', 'host/session-removed', 'host/workspace-changed', 'host/workspace-removed', 'host/workspace-order-changed', 'host/archived-sessions-changed'].includes(f.type)) return scheduleRefresh()
|
|
1704
2261
|
if (f.type === 'host/session-activity') {
|
|
1705
2262
|
const session = state.byId.get(f.sessionId)
|
|
@@ -1710,7 +2267,7 @@ function onHostFrame(full) {
|
|
|
1710
2267
|
if (f.type === 'host/session-status') {
|
|
1711
2268
|
if (f.running && state.runtimeErrors?.delete(f.sessionId) && state.current === f.sessionId) renderHistory()
|
|
1712
2269
|
const s = state.byId.get(f.sessionId)
|
|
1713
|
-
if (s) { s.running = f.running; if (f.running) s.error = false; if (state.current === f.sessionId) { renderSessionCards(); updateCancelBtn(); renderSessionSub(); updateSessionStatus() } }
|
|
2270
|
+
if (s) { s.running = f.running; if (f.running) s.error = false; if (state.current === f.sessionId) { renderSessionCards(); updateCancelBtn(); renderSessionSub(); updateSessionStatus(); renderQueue() } }
|
|
1714
2271
|
if (!f.running) scheduleSessionSync(f.sessionId)
|
|
1715
2272
|
return
|
|
1716
2273
|
}
|
|
@@ -1845,6 +2402,8 @@ function observeCompactionEvent(sessionId, event, meta = {}) {
|
|
|
1845
2402
|
|
|
1846
2403
|
function onSessionEvent(sessionId, event, meta = {}) {
|
|
1847
2404
|
if (!event) return
|
|
2405
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.handleEvent?.(sessionId, event)
|
|
2406
|
+
if (typeof turnDiffController !== 'undefined') turnDiffController?.handleEvent?.(sessionId, event)
|
|
1848
2407
|
if (['agent/status', 'agent/error', 'turn/start', 'turn/end', 'goal/completed'].includes(event.type) && typeof window !== 'undefined' && window.NativeBackground?.handleTaskEvent) window.NativeBackground.handleTaskEvent(bgBase(), state.token || '', JSON.stringify({ payload: { sessionId, event } }), meta.replay === true)
|
|
1849
2408
|
const s = state.byId.get(sessionId)
|
|
1850
2409
|
observeCompactionEvent(sessionId, event, meta)
|
|
@@ -1869,6 +2428,7 @@ function onSessionEvent(sessionId, event, meta = {}) {
|
|
|
1869
2428
|
if (state.current === sessionId) renderSessionTitle()
|
|
1870
2429
|
}
|
|
1871
2430
|
if (state.current === sessionId) insertLiveEvent(event)
|
|
2431
|
+
if (['plan/mode', 'tool/call', 'tool/result'].includes(event.type) && typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
1872
2432
|
if (['goal/created', 'goal/updated', 'goal/completed', 'goal/cleared', 'todo/updated', 'plan/updated', 'checkpoint/created'].includes(event.type)) scheduleRefresh()
|
|
1873
2433
|
}
|
|
1874
2434
|
|
|
@@ -1893,7 +2453,7 @@ async function refreshSessions() {
|
|
|
1893
2453
|
if (!v) {
|
|
1894
2454
|
// 网关不可达: 用上次成功的会话列表兜底, 用户仍能打开历史缓存
|
|
1895
2455
|
if (!state.sessions.length) {
|
|
1896
|
-
const cached =
|
|
2456
|
+
const cached = readCachedSessions()
|
|
1897
2457
|
if (Array.isArray(cached) && cached.length) {
|
|
1898
2458
|
state.sessions = cached
|
|
1899
2459
|
state.byId = new Map(cached.map(s => [s.sessionId, s]))
|
|
@@ -1912,15 +2472,16 @@ async function refreshSessions() {
|
|
|
1912
2472
|
state.subagentSessions[id] = merged
|
|
1913
2473
|
}
|
|
1914
2474
|
applyPendingProjections()
|
|
1915
|
-
|
|
2475
|
+
writeSessionCache(state.sessions)
|
|
1916
2476
|
if(typeof window!=='undefined')window.DshDoctorEntry?.consumeSessionLink(openSession,state.byId)
|
|
1917
2477
|
renderSessions()
|
|
1918
2478
|
refreshWorkbench()
|
|
2479
|
+
if (typeof sessionManager !== 'undefined') sessionManager?.hydrate?.()
|
|
1919
2480
|
}
|
|
1920
2481
|
|
|
1921
2482
|
function removeLocalSessionRecord(sessionId) {
|
|
1922
2483
|
if (!sessionId) return
|
|
1923
|
-
void window.DshHistory.cacheRemove(
|
|
2484
|
+
for (const scope of connectionCacheReadKeys('history')) void window.DshHistory.cacheRemove(scope,sessionId)
|
|
1924
2485
|
state.sessions = state.sessions.filter(session => session?.sessionId !== sessionId)
|
|
1925
2486
|
state.byId.delete(sessionId)
|
|
1926
2487
|
state.pendingProjections.delete(sessionId)
|
|
@@ -1929,7 +2490,7 @@ function removeLocalSessionRecord(sessionId) {
|
|
|
1929
2490
|
delete state.queues[sessionId]
|
|
1930
2491
|
delete state.jobs[sessionId]
|
|
1931
2492
|
LS.del(historyCacheScope()) // Also discard the obsolete monolithic cache.
|
|
1932
|
-
|
|
2493
|
+
writeSessionCache(state.sessions)
|
|
1933
2494
|
}
|
|
1934
2495
|
|
|
1935
2496
|
function proj(s, key, d) { return s?.projections?.values?.[key] ?? d }
|
|
@@ -2052,8 +2613,10 @@ function rememberRuntimeError(sessionId, message) {
|
|
|
2052
2613
|
if (sessionId === state.current) { renderHistory(); scheduleSessionSync(sessionId) }
|
|
2053
2614
|
}
|
|
2054
2615
|
function resyncAfterStreamOpen() {
|
|
2616
|
+
if (typeof hostSchedule !== 'undefined') void hostSchedule?.refresh(true)
|
|
2055
2617
|
if (!state.current || Date.now() - state.lastStreamResyncAt < 1200) return
|
|
2056
2618
|
state.lastStreamResyncAt = Date.now()
|
|
2619
|
+
if (typeof hostQueue !== 'undefined') hostQueue?.reconnect()
|
|
2057
2620
|
scheduleSessionSync(state.current, 0)
|
|
2058
2621
|
}
|
|
2059
2622
|
function sessionTitleValue(s) {
|
|
@@ -2107,8 +2670,12 @@ function setGoalCollapsed(sessionId, goal, collapsed) {
|
|
|
2107
2670
|
|
|
2108
2671
|
function updatePendingBadge() {
|
|
2109
2672
|
const pending = state.approvals.length + state.questions.length
|
|
2110
|
-
|
|
2111
|
-
|
|
2673
|
+
for (const id of ['nav-pending', 'group-drawer-pending']) {
|
|
2674
|
+
const badge = $(id)
|
|
2675
|
+
if (!badge) continue
|
|
2676
|
+
badge.classList.toggle('hidden', pending === 0)
|
|
2677
|
+
badge.textContent = pending || ''
|
|
2678
|
+
}
|
|
2112
2679
|
}
|
|
2113
2680
|
|
|
2114
2681
|
/* ---------------- 工作台与归档会话 ---------------- */
|
|
@@ -2176,7 +2743,10 @@ function orderedWorkspaceItems(items) {
|
|
|
2176
2743
|
}
|
|
2177
2744
|
function orderedWorkspaceSessions(workspaceId, items) {
|
|
2178
2745
|
const { value } = workbenchOrderScopeValue()
|
|
2179
|
-
|
|
2746
|
+
const pinned = new Set(state.wbPinned || [])
|
|
2747
|
+
const ordered = orderedItems(items, value.sessionIds?.[String(workspaceId)], item => item.sessionId)
|
|
2748
|
+
// Host pinning outranks the client-side manual order in every grouped view.
|
|
2749
|
+
return ordered.sort((a, b) => Number(pinned.has(b.sessionId)) - Number(pinned.has(a.sessionId)))
|
|
2180
2750
|
}
|
|
2181
2751
|
function saveWorkbenchOrder(mutator) {
|
|
2182
2752
|
const { store, value } = workbenchOrderScopeValue()
|
|
@@ -2246,7 +2816,7 @@ function renderWorkspaceNavigation() {
|
|
|
2246
2816
|
}
|
|
2247
2817
|
const selectedWorkspace = workspaceById(state.workspaceFilter)
|
|
2248
2818
|
const pathBox = $('session-workspace-path')
|
|
2249
|
-
if (pathBox) pathBox.textContent = selectedWorkspace?.path ||
|
|
2819
|
+
if (pathBox) pathBox.textContent = selectedWorkspace?.path || ''
|
|
2250
2820
|
const filesButton = $('session-workspace-files')
|
|
2251
2821
|
if (filesButton) filesButton.disabled = !selectedWorkspace
|
|
2252
2822
|
|
|
@@ -2291,10 +2861,12 @@ async function refreshWorkbench({ discover = false } = {}) {
|
|
|
2291
2861
|
if (!valid()) return
|
|
2292
2862
|
if (value) state.wbProjects = Array.isArray(value.items) ? value.items : []
|
|
2293
2863
|
if (value) state.wbArchived = Array.isArray(value.archivedSessionIds) ? value.archivedSessionIds : []
|
|
2864
|
+
if (value) state.wbPinned = Array.isArray(value.pinnedSessionIds) ? value.pinnedSessionIds : []
|
|
2294
2865
|
} catch {
|
|
2295
2866
|
if (!valid()) return
|
|
2296
2867
|
state.wbProjects = []
|
|
2297
2868
|
state.wbArchived = []
|
|
2869
|
+
state.wbPinned = []
|
|
2298
2870
|
}
|
|
2299
2871
|
// 以磁盘实际目录为准同步工作台项目:删除目录后不再残留,新增子目录自动收纳。
|
|
2300
2872
|
if (discover && state.wb?.bound && state.wb.path) {
|
|
@@ -2330,6 +2902,7 @@ async function refreshWorkbench({ discover = false } = {}) {
|
|
|
2330
2902
|
renderWorkspaceNavigation()
|
|
2331
2903
|
renderWorkbench()
|
|
2332
2904
|
renderSessions()
|
|
2905
|
+
if (typeof sessionManager !== 'undefined') sessionManager?.hydrate?.()
|
|
2333
2906
|
}
|
|
2334
2907
|
function renderWorkbench() {
|
|
2335
2908
|
const bar = $('workbench-bar')
|
|
@@ -2431,20 +3004,25 @@ function commitWorkspaceGroupOrder(order) {
|
|
|
2431
3004
|
}
|
|
2432
3005
|
function sortedSessions() {
|
|
2433
3006
|
const items = topLevelSessions()
|
|
3007
|
+
const pinned = new Set(state.wbPinned || [])
|
|
3008
|
+
const pinRank = session => pinned.has(session.sessionId) ? 0 : 1
|
|
2434
3009
|
if (state.sessionSort === 'workspace') {
|
|
2435
3010
|
return items.sort((a, b) => {
|
|
3011
|
+
const byPin = pinRank(a) - pinRank(b)
|
|
3012
|
+
if (byPin) return byPin
|
|
2436
3013
|
const aw = sessionCwd(a) || '\uffff'
|
|
2437
3014
|
const bw = sessionCwd(b) || '\uffff'
|
|
2438
3015
|
const byWorkspace = aw.localeCompare(bw, undefined, { numeric: true, sensitivity: 'base' })
|
|
2439
3016
|
return byWorkspace || (sessionSortTime(b) - sessionSortTime(a))
|
|
2440
3017
|
})
|
|
2441
3018
|
}
|
|
2442
|
-
return items.sort((a, b) => sessionSortTime(b) - sessionSortTime(a))
|
|
3019
|
+
return items.sort((a, b) => pinRank(a) - pinRank(b) || sessionSortTime(b) - sessionSortTime(a))
|
|
2443
3020
|
}
|
|
2444
3021
|
function renderSessions() {
|
|
2445
3022
|
const list = $('session-list')
|
|
2446
3023
|
const allItems = sortedSessions()
|
|
2447
3024
|
const archivedSet = new Set(state.wbArchived || [])
|
|
3025
|
+
const pinnedSet = new Set(state.wbPinned || [])
|
|
2448
3026
|
const visible = allItems.filter(s => {
|
|
2449
3027
|
if (!state.workspaceFilter) return true
|
|
2450
3028
|
if (state.workspaceFilter === WORKSPACE_UNGROUPED) return !workspaceForSession(s)
|
|
@@ -2457,6 +3035,7 @@ function renderSessions() {
|
|
|
2457
3035
|
const workspace = sessionWorkspaceLabel(s)
|
|
2458
3036
|
const workspaceTitle = sessionWorkspaceName(s)
|
|
2459
3037
|
const title = sessionLabelOf(s)
|
|
3038
|
+
const isPinned = pinnedSet.has(s.sessionId)
|
|
2460
3039
|
const goal = goalOf(s)
|
|
2461
3040
|
const pending = (state.approvals.some(a => a.sessionId === s.sessionId) || state.questions.some(q => q.sessionId === s.sessionId)) ? 'pending' : ''
|
|
2462
3041
|
const queueN = (state.queues[s.sessionId] || []).filter(i => i.placement === 'queued').length
|
|
@@ -2465,18 +3044,22 @@ function renderSessions() {
|
|
|
2465
3044
|
if (pending) dots.push('pending')
|
|
2466
3045
|
const badge = goal ? `<span class="sc-badge ${goal.phase === 'active' ? 'goal-active' : ''}">${esc(t('sessions.goalBadge', { phase: goal.phase || '?' }))}</span>` : ''
|
|
2467
3046
|
const queueBadge = queueN ? `<span class="sc-badge">${esc(t('sessions.queueBadge', { n: queueN }))}</span>` : ''
|
|
2468
|
-
const archiveButton = archivedSet.has(s.sessionId)
|
|
3047
|
+
const archiveButton = archivedSet.has(s.sessionId)
|
|
3048
|
+
? `<button type="button" class="sc-archive-btn" data-unarchive-session="${esc(s.sessionId)}">${esc(t('session.unarchive'))}</button>`
|
|
3049
|
+
: `<button type="button" class="sc-archive-btn" data-archive-session="${esc(s.sessionId)}">${esc(t('session.archive'))}</button>`
|
|
2469
3050
|
return `<div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}" role="button" tabindex="0" aria-label="${esc(sessionLabelOf(s))}">
|
|
2470
3051
|
<div class="session-card ${state.current === s.sessionId ? 'current' : ''}">
|
|
2471
|
-
<div class="sc-title">${esc(title)}</div>
|
|
3052
|
+
<div class="sc-title">${isPinned ? '<span class="sc-pin" aria-label="' + esc(t('sessions.pinned')) + '">📌</span> ' : ''}${esc(title)}</div>
|
|
2472
3053
|
<div class="sc-meta">
|
|
2473
|
-
<span class="sc-
|
|
3054
|
+
<span class="sc-workspace" title="${esc(workspace)}">${esc(workspaceTitle)}</span>
|
|
2474
3055
|
<span>${fmtTime(sessionSortTime(s))}</span>
|
|
3056
|
+
</div>
|
|
3057
|
+
${dots.length || badge || queueBadge ? `<div class="sc-status">
|
|
3058
|
+
${dots.length ? `<span class="sc-dot ${dots.join(' ')}"></span>` : ''}
|
|
2475
3059
|
${s.running ? '<span>' + t('sessions.running') + '</span>' : ''}
|
|
2476
3060
|
${badge}${queueBadge}
|
|
2477
|
-
</div
|
|
2478
|
-
<
|
|
2479
|
-
<span class="sc-arrow">›</span>
|
|
3061
|
+
</div>` : ''}
|
|
3062
|
+
<span class="sc-arrow" aria-hidden="true">›</span>
|
|
2480
3063
|
</div>
|
|
2481
3064
|
${archiveButton}
|
|
2482
3065
|
</div>`
|
|
@@ -2526,6 +3109,7 @@ function renderSessions() {
|
|
|
2526
3109
|
<div class="stat pending"><div class="v">${pending}</div><div class="k">${t('sessions.statPending')}</div></div>
|
|
2527
3110
|
<div class="stat ctx"><div class="v">${visible.length}</div><div class="k">${t('sessions.statTotal')}</div></div>`
|
|
2528
3111
|
updatePendingBadge()
|
|
3112
|
+
renderGroupDrawerSessions()
|
|
2529
3113
|
}
|
|
2530
3114
|
|
|
2531
3115
|
/* ---------------- 会话详情 ---------------- */
|
|
@@ -2582,6 +3166,8 @@ async function openSession(id) {
|
|
|
2582
3166
|
}
|
|
2583
3167
|
cancelHistoryLoad()
|
|
2584
3168
|
state.current = id
|
|
3169
|
+
if (typeof syncComposerToolsScope === 'function') syncComposerToolsScope()
|
|
3170
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.setSession?.(id)
|
|
2585
3171
|
setSessionRecovery('loading')
|
|
2586
3172
|
state.history = emptyHistory()
|
|
2587
3173
|
const openingHistory=state.history, openingConnection=captureConnection()
|
|
@@ -2597,6 +3183,7 @@ async function openSession(id) {
|
|
|
2597
3183
|
$('history').innerHTML = '<div class="empty">' + t('history.loading') + '</div>'
|
|
2598
3184
|
renderQueue()
|
|
2599
3185
|
renderSessionPending()
|
|
3186
|
+
if (typeof hostQueue !== 'undefined') hostQueue?.reconnect()
|
|
2600
3187
|
void refreshCompactionStatus(id)
|
|
2601
3188
|
getConversationView().reset()
|
|
2602
3189
|
try { const restored=await restoreCachedHistory();globalThis.DshDiagnostics?.record('history.cache',{phase:restored?'hit':'miss',sessionId:id}) } catch(error) {
|
|
@@ -2645,6 +3232,10 @@ async function closeSession() {
|
|
|
2645
3232
|
const connection=captureConnection(),discard=!wasLoading&&shouldDiscardEmptySession(sessionId)
|
|
2646
3233
|
state.current = null
|
|
2647
3234
|
if (typeof updateContextRing === 'function') updateContextRing()
|
|
3235
|
+
if (typeof syncComposerToolsScope === 'function') syncComposerToolsScope()
|
|
3236
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.setSession?.(null)
|
|
3237
|
+
if (typeof turnDiffController !== 'undefined') turnDiffController?.setSession?.(null)
|
|
3238
|
+
if (typeof planReviewHost !== 'undefined') planReviewHost?.classList.add('hidden')
|
|
2648
3239
|
state.history = emptyHistory()
|
|
2649
3240
|
document.body.classList.remove('in-session')
|
|
2650
3241
|
showView('view-home')
|
|
@@ -2670,12 +3261,15 @@ async function closeSession() {
|
|
|
2670
3261
|
function bindNativeBack() {
|
|
2671
3262
|
if (!CAP?.isNativePlatform?.()) return
|
|
2672
3263
|
try {
|
|
2673
|
-
CAP.Plugins?.App?.addListener?.('appStateChange',({isActive})=>{
|
|
3264
|
+
CAP.Plugins?.App?.addListener?.('appStateChange', ({ isActive }) => {
|
|
3265
|
+
if (isActive) onResume()
|
|
3266
|
+
else markRealtimeBackgrounded()
|
|
3267
|
+
})
|
|
2674
3268
|
CAP.Plugins?.App?.addListener?.('backButton', () => {
|
|
2675
3269
|
if (typeof window !== 'undefined' && window.DshSlashSuggestions?.close()) return
|
|
2676
3270
|
if ($('composer-wrap')?.classList.contains('fs')) { setComposerFullscreen(false); return }
|
|
2677
3271
|
if (customSelectCurrent) { closeCustomSelect(); return }
|
|
2678
|
-
if (groupDrawerOpen()) {
|
|
3272
|
+
if (groupDrawerOpen()) { backGroupDrawer(); return }
|
|
2679
3273
|
if (typeof window !== 'undefined' && window.DshImagePreview?.closeSaveMenu?.()) return
|
|
2680
3274
|
if (typeof window !== 'undefined' && window.DshImagePreview?.isOpen?.()) { window.DshImagePreview.close(); return }
|
|
2681
3275
|
if (typeof window !== 'undefined' && window.DshExtensions?.closeShortcuts(true)) return
|
|
@@ -2889,9 +3483,55 @@ function partialReasoningHtml() {
|
|
|
2889
3483
|
}
|
|
2890
3484
|
|
|
2891
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
|
+
|
|
2892
3525
|
function restoreCachedSessionList() {
|
|
2893
|
-
if(state.sessions.length)return
|
|
2894
|
-
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 {}
|
|
2895
3535
|
}
|
|
2896
3536
|
|
|
2897
3537
|
let conversationView = null
|
|
@@ -2923,15 +3563,21 @@ function scheduleHistoryCacheSave() {
|
|
|
2923
3563
|
}
|
|
2924
3564
|
async function saveHistoryCache(scope=historyCacheScope(),id=state.current,history=state.history) {
|
|
2925
3565
|
if(!id||!history.visible.length||history.tailEvicted)return
|
|
2926
|
-
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)
|
|
2927
3567
|
if(!saved&&state.current===id&&state.history===history&&scope===historyCacheScope())historySource('saveFailed')
|
|
2928
3568
|
if(saved&&state.current===id&&state.history===history&&scope===historyCacheScope()&&['synced','saveFailed'].includes(history.source))historySource('saved')
|
|
2929
3569
|
}
|
|
2930
3570
|
async function restoreCachedHistory() {
|
|
2931
|
-
const connection=captureConnection(),id=state.current,history=state.history
|
|
3571
|
+
const connection=captureConnection(),id=state.current,history=state.history
|
|
2932
3572
|
if(!id)return false
|
|
2933
|
-
const
|
|
2934
|
-
|
|
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
|
|
2935
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)
|
|
2936
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
|
|
2937
3583
|
if(cached.title&&!hasSessionTitle(state.byId.get(id)))hydrateSessionProjections(id,{values:{title:cached.title},asOfSeq:0})
|
|
@@ -3023,7 +3669,7 @@ async function loadHistory(reset = true) {
|
|
|
3023
3669
|
history.renderError=!!getConversationView().renderErrors
|
|
3024
3670
|
historySource(history.renderError?'error':'synced');setSessionRecovery(history.renderError?'error':'ready')
|
|
3025
3671
|
if(approvalChanged)renderApprovalRecords()
|
|
3026
|
-
$('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})
|
|
3027
3673
|
diagnostic?.end({phase:history.renderError?'failed':'rendered',count:history.visible.length,renderedCount:getConversationView().end-getConversationView().start,renderErrors:getConversationView().renderErrors||0})
|
|
3028
3674
|
if(!history.renderError)scheduleHistoryCacheSave()
|
|
3029
3675
|
} catch(error) { failLoad(error,true) }
|
|
@@ -3086,6 +3732,7 @@ function bindTurnResultActions() {
|
|
|
3086
3732
|
if (!state.byId.has(id)) {
|
|
3087
3733
|
const branch = { ...parent, projections: parent?.projections ? { ...JSON.parse(JSON.stringify(parent.projections)), asOfSeq: 0 } : undefined,
|
|
3088
3734
|
sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
|
|
3735
|
+
if (branch.projections?.values) delete branch.projections.values.conversationContinuation
|
|
3089
3736
|
state.byId.set(id, branch)
|
|
3090
3737
|
state.sessions.unshift(branch)
|
|
3091
3738
|
renderSessions()
|
|
@@ -3099,7 +3746,7 @@ function renderHistory(reset=false,mode='auto') {
|
|
|
3099
3746
|
const filtered=filteredEntries(),toolNames=new Map()
|
|
3100
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)}
|
|
3101
3748
|
state.history.toolNames=toolNames
|
|
3102
|
-
$('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})
|
|
3103
3750
|
let prepared=window.DshActivity?.prepare(filtered)||filtered
|
|
3104
3751
|
// 弱网精简:尚未返回的调用在完成前不展示,只留已完成的消息与工具结果。
|
|
3105
3752
|
if(weakStreamTrim())prepared=prepared.filter(entry=>entry.event?.type!=='tool/call'||entry.view?.toolActivity)
|
|
@@ -3117,12 +3764,36 @@ function renderHistory(reset=false,mode='auto') {
|
|
|
3117
3764
|
prepared = window.DshTurnResults.decorate(prepared, state.history.visible, { sessionId: state.current, canFork: canForkTurnResult() })
|
|
3118
3765
|
bindTurnResultActions()
|
|
3119
3766
|
}
|
|
3767
|
+
if (typeof turnDiffController !== 'undefined' && turnDiffController) {
|
|
3768
|
+
turnDiffController.setLayout('mobile')
|
|
3769
|
+
turnDiffController.setSession(state.current)
|
|
3770
|
+
if (typeof turnDiffHtmlFor === 'function') prepared = prepared.map(entry => ({ ...entry, view: { ...entry.view, turnDiffHtml: turnDiffHtmlFor(entry) } }))
|
|
3771
|
+
}
|
|
3772
|
+
if (activity?.withContinuation && activeGatewayCapability('sessionContinuation') === true) {
|
|
3773
|
+
const sessionId = state.current, history = state.history, connection = captureConnection()
|
|
3774
|
+
const session = state.byId.get(sessionId)
|
|
3775
|
+
prepared = activity.withContinuation($('history'), prepared, {
|
|
3776
|
+
history, ending: session && session.origin !== 'subagent' && session.formatStatus !== 'migration-required'
|
|
3777
|
+
&& !(state.wbArchived || []).includes(sessionId)
|
|
3778
|
+
? proj(session, 'conversationContinuation') : undefined,
|
|
3779
|
+
valid: () => connection.valid() && state.current === sessionId && state.history === history,
|
|
3780
|
+
render: () => renderHistory(),
|
|
3781
|
+
submit: ending => rpc('session.continue', { sessionId, ending }),
|
|
3782
|
+
failed: error => {
|
|
3783
|
+
if (error.operationPending) notifyPendingOperation(error, connection)
|
|
3784
|
+
else if (connection.valid() && state.current === sessionId && state.history === history) {
|
|
3785
|
+
toast(error.message, 'err'); void resyncCurrentSession()
|
|
3786
|
+
}
|
|
3787
|
+
},
|
|
3788
|
+
})
|
|
3789
|
+
}
|
|
3120
3790
|
if(window.DshActivity?.groupFailures)prepared=window.DshActivity.groupFailures(prepared)
|
|
3121
3791
|
const hostError = state.runtimeErrors?.get(state.current)
|
|
3122
3792
|
const recordedError = state.history.visible.some(entry => window.DshActivity?.failure?.(entry.event)?.message === hostError)
|
|
3123
3793
|
const runtimeHtml = hostError && !recordedError ? window.DshActivity?.failureHtml?.(hostError) || '' : ''
|
|
3124
3794
|
getConversationView().set(prepared,{reset,follow:mode==='bottom',live:(groupLive?'':partialReasoningHtml())+runtimeHtml,hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('history.empty')})
|
|
3125
3795
|
window.DshImagePreview?.hydrate?.($('history'))
|
|
3796
|
+
if (typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
3126
3797
|
}
|
|
3127
3798
|
window.applyStreamPreference=()=>{if(state.current)renderHistory(false,'auto')}
|
|
3128
3799
|
|
|
@@ -3187,7 +3858,8 @@ const INTERESTING_EVENTS = new Set([
|
|
|
3187
3858
|
'goal/created', 'goal/updated', 'goal/completed', 'goal/cleared',
|
|
3188
3859
|
'todo/updated', 'plan/updated',
|
|
3189
3860
|
'question/asked', 'question/resolved',
|
|
3190
|
-
'approval/asked', 'approval/resolved'
|
|
3861
|
+
'approval/asked', 'approval/resolved',
|
|
3862
|
+
'deliverables/presented', 'workspace/changes'
|
|
3191
3863
|
])
|
|
3192
3864
|
function messageSource(data) {
|
|
3193
3865
|
const source = data?.source ?? data?.message?.source
|
|
@@ -3221,10 +3893,12 @@ function eventHtml(entry, ctx = {}) {
|
|
|
3221
3893
|
const ev = entry.event || {}
|
|
3222
3894
|
const data = ev.data || {}
|
|
3223
3895
|
const type = ev.type || 'event'
|
|
3224
|
-
const failure = window.DshActivity?.failureHtml?.(window.DshActivity.failure(ev)) || ''
|
|
3896
|
+
const failure = window.DshActivity?.failureHtml?.(window.DshActivity.failure(ev), false, entry.view?.continuation) || ''
|
|
3225
3897
|
if (entry.view?.turnResult) return failure + window.DshTurnResults.html(entry.view.turnResult)
|
|
3226
3898
|
// Successful boundaries stay quiet; failed turns keep their durable explanation.
|
|
3227
|
-
if (type === 'turn/start'
|
|
3899
|
+
if (type === 'turn/start') return failure
|
|
3900
|
+
if (type === 'turn/end') return failure + (entry.view?.turnDiffHtml || '')
|
|
3901
|
+
if (type === 'deliverables/presented' || type === 'workspace/changes') return ''
|
|
3228
3902
|
if (type === 'assistant/attempt') return window.DshActivity?.attemptHtml?.(ev) || ''
|
|
3229
3903
|
if (entry.view?.activityTurn) return window.DshActivity.turnHtml(entry.view.activityTurn)
|
|
3230
3904
|
if (entry.view?.activityGroup) return window.DshActivity.groupHtml(entry.view.activityGroup, item => eventHtml(item, ctx))
|
|
@@ -3694,6 +4368,16 @@ async function sendSessionText(text) {
|
|
|
3694
4368
|
}
|
|
3695
4369
|
|
|
3696
4370
|
let composerSending = false
|
|
4371
|
+
let composerTools = null
|
|
4372
|
+
let sessionSearchController = null
|
|
4373
|
+
let sessionSearchMount = null
|
|
4374
|
+
let sessionSearchConnection = null
|
|
4375
|
+
let sessionManager = null
|
|
4376
|
+
let workspaceAdminMount = null
|
|
4377
|
+
let planReviewController = null
|
|
4378
|
+
let planReviewHost = null
|
|
4379
|
+
let turnDiffController = null
|
|
4380
|
+
let turnDiffRoot = null
|
|
3697
4381
|
const composerSendFeedback = new Map()
|
|
3698
4382
|
const steeringInFlight = new Set()
|
|
3699
4383
|
function composerContext() { return `${state.server}\0${state.current}` }
|
|
@@ -3907,16 +4591,23 @@ async function sendMessage(requestedMode) {
|
|
|
3907
4591
|
const input = $('composer-input')
|
|
3908
4592
|
if (typeof window !== 'undefined') window.DshSlashSuggestions?.close()
|
|
3909
4593
|
const originalText = input.value
|
|
3910
|
-
const
|
|
4594
|
+
const clean = originalText.trim()
|
|
4595
|
+
// Quoted selections are composed into the same user message as Markdown
|
|
4596
|
+
// blockquotes; the Host receives one ordinary prompt and sees no client-made
|
|
4597
|
+
// approval/reference side channel. A slash command keeps its leading token.
|
|
4598
|
+
const quoted = clean && !clean.startsWith('/') && typeof composerTools !== 'undefined' ? composerTools?.quotes() || [] : []
|
|
4599
|
+
const quoteText = quoted.length ? window.DshComposerTools.formatQuotes(quoted) : ''
|
|
4600
|
+
const text = [quoteText, clean].filter(Boolean).join('\n\n')
|
|
3911
4601
|
const context = composerContext()
|
|
3912
4602
|
const images = state.composerImages.slice()
|
|
3913
4603
|
if ((!text && !images.length) || !state.current) return
|
|
3914
|
-
if (images.length &&
|
|
4604
|
+
if (images.length && clean.startsWith('/')) { toast(t('composer.imageSlashUnsupported'), 'err'); return }
|
|
3915
4605
|
const mode = typeof requestedMode === 'string' ? requestedMode : composerSendMode()
|
|
3916
4606
|
if (await sendSessionContent(text, images, mode) && composerContext() === context) {
|
|
3917
4607
|
if (input.value === originalText) { input.value = ''; autosize(input) }
|
|
3918
|
-
if (typeof composerDrafts !== 'undefined' && composerDrafts.get(state.current) ===
|
|
4608
|
+
if (typeof composerDrafts !== 'undefined' && composerDrafts.get(state.current) === originalText) composerDrafts.delete(state.current)
|
|
3919
4609
|
if (state.composerImages.length === images.length && images.every((item, i) => item === state.composerImages[i])) clearComposerImages()
|
|
4610
|
+
if (quoted.length) composerTools?.clearQuotes(quoted.map(quote => quote.id))
|
|
3920
4611
|
}
|
|
3921
4612
|
}
|
|
3922
4613
|
|
|
@@ -3925,6 +4616,488 @@ function hideComposerMenu() {
|
|
|
3925
4616
|
$('btn-plus').classList.remove('active')
|
|
3926
4617
|
}
|
|
3927
4618
|
|
|
4619
|
+
/* ---------------- B/C 输入、搜索与管理 ---------------- */
|
|
4620
|
+
function bcEnglish() { return I18N.lang === 'en' }
|
|
4621
|
+
function bcText(zh, en) { return bcEnglish() ? en : zh }
|
|
4622
|
+
|
|
4623
|
+
async function bcRpc(method, payload, options = {}) {
|
|
4624
|
+
return rpc(method, payload, Number.isFinite(options.timeoutMs) ? options.timeoutMs : 45000, options.signal || null)
|
|
4625
|
+
}
|
|
4626
|
+
|
|
4627
|
+
function composerToolsHost() {
|
|
4628
|
+
return {
|
|
4629
|
+
scope: () => ({ key: JSON.stringify([connectionGeneration, state.current]), sessionId: state.current || '', connection: captureConnection() }),
|
|
4630
|
+
async listReferences(scope, query) {
|
|
4631
|
+
const sessionId = scope?.sessionId || state.current
|
|
4632
|
+
if (!sessionId) return null
|
|
4633
|
+
const [files, sessions] = await Promise.allSettled([
|
|
4634
|
+
bcRpc('fileReferences.list', { sessionId, query: String(query || '') }, { timeoutMs: 12000 }),
|
|
4635
|
+
bcRpc('sessionReferenceResolver.candidates', { sessionId, query: String(query || '') }, { timeoutMs: 12000 }),
|
|
4636
|
+
])
|
|
4637
|
+
if (files.status !== 'fulfilled' && sessions.status !== 'fulfilled') return null
|
|
4638
|
+
const references = []
|
|
4639
|
+
if (files.status === 'fulfilled' && Array.isArray(files.value)) {
|
|
4640
|
+
for (const row of files.value) {
|
|
4641
|
+
const insert = window.DshComposerTools.fileReferenceMention(row)
|
|
4642
|
+
if (!insert) continue
|
|
4643
|
+
references.push({
|
|
4644
|
+
insert,
|
|
4645
|
+
label: row?.kind === 'directory' ? String(row?.path || '') + '/' : String(row?.path || ''),
|
|
4646
|
+
detail: row?.kind === 'directory' ? bcText('目录', 'Directory') : bcText('文件', 'File'),
|
|
4647
|
+
kind: 'file',
|
|
4648
|
+
allowed: true,
|
|
4649
|
+
})
|
|
4650
|
+
}
|
|
4651
|
+
}
|
|
4652
|
+
if (sessions.status === 'fulfilled' && Array.isArray(sessions.value)) {
|
|
4653
|
+
for (const row of sessions.value) {
|
|
4654
|
+
if (typeof row?.mention !== 'string' || !row.mention.startsWith('@')) continue
|
|
4655
|
+
references.push({
|
|
4656
|
+
insert: row.mention,
|
|
4657
|
+
label: row.displayTitle || row.label || row.sessionId || '',
|
|
4658
|
+
detail: row.cwd || '',
|
|
4659
|
+
kind: 'session',
|
|
4660
|
+
allowed: true,
|
|
4661
|
+
})
|
|
4662
|
+
}
|
|
4663
|
+
}
|
|
4664
|
+
return { supported: true, references }
|
|
4665
|
+
},
|
|
4666
|
+
notice: (text, kind) => toast(text, kind === 'err' ? 'err' : ''),
|
|
4667
|
+
}
|
|
4668
|
+
}
|
|
4669
|
+
|
|
4670
|
+
let quoteSelectionButton = null
|
|
4671
|
+
function selectedMessageQuote() {
|
|
4672
|
+
const selection = window.getSelection?.()
|
|
4673
|
+
if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null
|
|
4674
|
+
const range = selection.getRangeAt(0)
|
|
4675
|
+
const history = $('history')
|
|
4676
|
+
if (!history || !range.commonAncestorContainer) return null
|
|
4677
|
+
const startNode = range.startContainer.nodeType === 3 ? range.startContainer.parentElement : range.startContainer
|
|
4678
|
+
const endNode = range.endContainer.nodeType === 3 ? range.endContainer.parentElement : range.endContainer
|
|
4679
|
+
const startMessage = startNode?.closest?.('.msg')
|
|
4680
|
+
const endMessage = endNode?.closest?.('.msg')
|
|
4681
|
+
if (!startMessage || !endMessage || startMessage !== endMessage || !history.contains(startMessage)) return null
|
|
4682
|
+
const text = selection.toString().replace(/\r\n?/g, '\n').trim()
|
|
4683
|
+
if (!text) return null
|
|
4684
|
+
const role = startMessage.classList.contains('user') ? 'user' : startMessage.classList.contains('assistant') ? 'assistant' : ''
|
|
4685
|
+
const messageId = startMessage.dataset.seq || ''
|
|
4686
|
+
const rect = range.getBoundingClientRect()
|
|
4687
|
+
return { text, role, messageId, rect }
|
|
4688
|
+
}
|
|
4689
|
+
|
|
4690
|
+
function hideQuoteSelectionButton() {
|
|
4691
|
+
if (!quoteSelectionButton) return
|
|
4692
|
+
quoteSelectionButton.hidden = true
|
|
4693
|
+
quoteSelectionButton.classList.add('hidden')
|
|
4694
|
+
}
|
|
4695
|
+
|
|
4696
|
+
function updateQuoteSelectionButton() {
|
|
4697
|
+
if (!quoteSelectionButton || !composerTools) return
|
|
4698
|
+
const selected = selectedMessageQuote()
|
|
4699
|
+
if (!selected) { hideQuoteSelectionButton(); return }
|
|
4700
|
+
const rect = selected.rect
|
|
4701
|
+
const x = Math.max(8, Math.min(window.innerWidth - 150, rect.left + rect.width / 2 - 70))
|
|
4702
|
+
const y = Math.max(8, Math.min(window.innerHeight - 56, rect.bottom + 8))
|
|
4703
|
+
quoteSelectionButton.style.left = x + 'px'
|
|
4704
|
+
quoteSelectionButton.style.top = y + 'px'
|
|
4705
|
+
quoteSelectionButton.hidden = false
|
|
4706
|
+
quoteSelectionButton.classList.remove('hidden')
|
|
4707
|
+
quoteSelectionButton.dataset.ready = '1'
|
|
4708
|
+
}
|
|
4709
|
+
|
|
4710
|
+
function initQuoteSelection() {
|
|
4711
|
+
if (quoteSelectionButton) return
|
|
4712
|
+
quoteSelectionButton = document.createElement('button')
|
|
4713
|
+
quoteSelectionButton.type = 'button'
|
|
4714
|
+
quoteSelectionButton.className = 'ct-quote-pick hidden'
|
|
4715
|
+
quoteSelectionButton.hidden = true
|
|
4716
|
+
quoteSelectionButton.textContent = t('composer.quoteSelection')
|
|
4717
|
+
quoteSelectionButton.addEventListener('pointerdown', event => event.preventDefault())
|
|
4718
|
+
quoteSelectionButton.addEventListener('click', event => {
|
|
4719
|
+
event.preventDefault()
|
|
4720
|
+
const selected = selectedMessageQuote()
|
|
4721
|
+
hideQuoteSelectionButton()
|
|
4722
|
+
if (!selected || !composerTools) return
|
|
4723
|
+
composerTools.addQuote({ messageId: selected.messageId, role: selected.role, text: selected.text })
|
|
4724
|
+
window.getSelection?.()?.removeAllRanges?.()
|
|
4725
|
+
toast(t('composer.quoteAdded'), 'ok')
|
|
4726
|
+
})
|
|
4727
|
+
document.body.append(quoteSelectionButton)
|
|
4728
|
+
document.addEventListener('selectionchange', () => {
|
|
4729
|
+
if (document.activeElement === $('composer-input')) return
|
|
4730
|
+
updateQuoteSelectionButton()
|
|
4731
|
+
})
|
|
4732
|
+
window.addEventListener('scroll', hideQuoteSelectionButton, { passive: true })
|
|
4733
|
+
window.addEventListener('resize', hideQuoteSelectionButton)
|
|
4734
|
+
}
|
|
4735
|
+
|
|
4736
|
+
function initComposerToolsUi() {
|
|
4737
|
+
if (composerTools || !window.DshComposerTools) return
|
|
4738
|
+
const input = $('composer-input')
|
|
4739
|
+
const composer = input?.closest?.('.composer')
|
|
4740
|
+
const wrap = $('composer-wrap')
|
|
4741
|
+
if (!input || !composer || !wrap) return
|
|
4742
|
+
const anchor = document.createElement('div')
|
|
4743
|
+
anchor.className = 'ct-anchor'
|
|
4744
|
+
const menu = document.createElement('div')
|
|
4745
|
+
menu.id = 'composer-tools-menu'
|
|
4746
|
+
menu.className = 'ct-menu hidden'
|
|
4747
|
+
menu.hidden = true
|
|
4748
|
+
anchor.append(menu)
|
|
4749
|
+
const quotes = document.createElement('div')
|
|
4750
|
+
quotes.id = 'composer-tools-quotes'
|
|
4751
|
+
quotes.className = 'ct-quotes hidden'
|
|
4752
|
+
quotes.hidden = true
|
|
4753
|
+
const hint = document.createElement('p')
|
|
4754
|
+
hint.id = 'composer-tools-hint'
|
|
4755
|
+
hint.className = 'ct-hint hidden'
|
|
4756
|
+
hint.hidden = true
|
|
4757
|
+
composer.before(anchor)
|
|
4758
|
+
composer.before(quotes)
|
|
4759
|
+
composer.before(hint)
|
|
4760
|
+
composerTools = window.DshComposerTools.create({
|
|
4761
|
+
input,
|
|
4762
|
+
menu,
|
|
4763
|
+
hint,
|
|
4764
|
+
quoteList: quotes,
|
|
4765
|
+
host: composerToolsHost(),
|
|
4766
|
+
commands: false,
|
|
4767
|
+
onChange: () => autosize(input),
|
|
4768
|
+
})
|
|
4769
|
+
initQuoteSelection()
|
|
4770
|
+
}
|
|
4771
|
+
|
|
4772
|
+
function syncComposerToolsScope() {
|
|
4773
|
+
composerTools?.setScope?.({ key: JSON.stringify([connectionGeneration, state.current]), sessionId: state.current || '', connection: captureConnection() })
|
|
4774
|
+
}
|
|
4775
|
+
|
|
4776
|
+
function sessionSearchAdapter() {
|
|
4777
|
+
return {
|
|
4778
|
+
rpc: bcRpc,
|
|
4779
|
+
sessions: () => (state.sessions || []).filter(s => s && s.sessionId && s.origin !== 'subagent' && s.blank !== true),
|
|
4780
|
+
workspaces: () => workspaceItems(),
|
|
4781
|
+
archivedSessionIds: () => state.wbArchived || [],
|
|
4782
|
+
pinnedSessionIds: () => state.wbPinned || [],
|
|
4783
|
+
titleOf: session => titleOf(session),
|
|
4784
|
+
historyRoot: () => $('history'),
|
|
4785
|
+
openSession: async (sessionId) => {
|
|
4786
|
+
closeGroupDrawer({ restoreFocus: false })
|
|
4787
|
+
await openSession(sessionId)
|
|
4788
|
+
},
|
|
4789
|
+
notice: (message) => toast(message),
|
|
4790
|
+
}
|
|
4791
|
+
}
|
|
4792
|
+
|
|
4793
|
+
function initSessionSearchUi() {
|
|
4794
|
+
if (!window.DshSessionSearch) return
|
|
4795
|
+
$('group-drawer-search')?.classList.remove('hidden')
|
|
4796
|
+
}
|
|
4797
|
+
|
|
4798
|
+
function refreshDrawerSearch() {
|
|
4799
|
+
if (!sessionSearchConnection?.valid()) {
|
|
4800
|
+
sessionSearchController?.cancelSearch()
|
|
4801
|
+
sessionSearchMount?.destroy()
|
|
4802
|
+
sessionSearchConnection = captureConnection()
|
|
4803
|
+
sessionSearchController = window.DshSessionSearch.init(sessionSearchAdapter())
|
|
4804
|
+
sessionSearchMount = window.DshSessionSearch.mount($('session-search-host'), sessionSearchController, {
|
|
4805
|
+
enhanceWorkspaceSelect: enhanceCustomSelect,
|
|
4806
|
+
})
|
|
4807
|
+
}
|
|
4808
|
+
sessionSearchController.syncCatalog()
|
|
4809
|
+
sessionSearchMount?.refresh()
|
|
4810
|
+
}
|
|
4811
|
+
|
|
4812
|
+
function workspaceRemovalConfirmation(request) {
|
|
4813
|
+
const impact = request?.impact || {}
|
|
4814
|
+
const lines = [
|
|
4815
|
+
bcText(`移除工作区登记「${request?.displayTitle || impact.name || ''}」?`, `Remove the workspace registration "${request?.displayTitle || impact.name || ''}"?`),
|
|
4816
|
+
bcText('只删除工作区登记,不删除磁盘目录、文件或会话历史。', 'Only the Workspace registration is removed; directories, files and conversation history stay on disk.'),
|
|
4817
|
+
bcText(`该工作区关联 ${impact.total || 0} 个会话${impact.archivedCount ? `(${impact.archivedCount} 个已归档)` : ''}。移除后这些会话将不再按该工作区分组。`, `${impact.total || 0} conversation(s) are associated${impact.archivedCount ? `, ${impact.archivedCount} archived` : ''}. Their Workspace grouping disappears after removal.`),
|
|
4818
|
+
]
|
|
4819
|
+
return window.confirm(lines.join('\n\n'))
|
|
4820
|
+
}
|
|
4821
|
+
|
|
4822
|
+
function promptWorkspaceTitle({ workspace, current }) {
|
|
4823
|
+
const value = window.prompt(t('workspace.renamePrompt'), current || workspace?.title || '')
|
|
4824
|
+
return value == null ? null : String(value)
|
|
4825
|
+
}
|
|
4826
|
+
|
|
4827
|
+
function initSessionManagementUi() {
|
|
4828
|
+
if (sessionManager || !window.DshSessionManagement) return
|
|
4829
|
+
sessionManager = window.DshSessionManagement.init({
|
|
4830
|
+
rpc: bcRpc,
|
|
4831
|
+
sessions: () => state.sessions,
|
|
4832
|
+
workspaces: () => workspaceItems(),
|
|
4833
|
+
archivedSessionIds: () => state.wbArchived || [],
|
|
4834
|
+
pinnedSessionIds: () => state.wbPinned || [],
|
|
4835
|
+
titleOf: session => titleOf(session),
|
|
4836
|
+
refresh: async () => { await Promise.all([refreshWorkbench(), refreshSessions()]) },
|
|
4837
|
+
confirm: workspaceRemovalConfirmation,
|
|
4838
|
+
promptTitle: promptWorkspaceTitle,
|
|
4839
|
+
toast,
|
|
4840
|
+
})
|
|
4841
|
+
const manageButton = document.createElement('button')
|
|
4842
|
+
manageButton.id = 'btn-manage-workspaces'
|
|
4843
|
+
manageButton.type = 'button'
|
|
4844
|
+
manageButton.className = 'mini-btn'
|
|
4845
|
+
manageButton.textContent = t('workspace.manage')
|
|
4846
|
+
$('session-workspace-files')?.after(manageButton)
|
|
4847
|
+
manageButton.addEventListener('click', openWorkspaceAdmin)
|
|
4848
|
+
const dialog = $('session-actions')
|
|
4849
|
+
if (dialog) {
|
|
4850
|
+
const box = document.createElement('div')
|
|
4851
|
+
box.id = 'session-admin-actions'
|
|
4852
|
+
dialog.querySelector('#btn-archive-session')?.before(box)
|
|
4853
|
+
window.DshSessionManagement.bindWorkspaceAdmin(box, sessionManager, {
|
|
4854
|
+
onResult: result => { if (result?.ok) renderSessions() },
|
|
4855
|
+
})
|
|
4856
|
+
}
|
|
4857
|
+
updateBcControlLabels()
|
|
4858
|
+
}
|
|
4859
|
+
|
|
4860
|
+
function ensureWorkspaceAdminModal() {
|
|
4861
|
+
let modal = $('modal-workspace-admin')
|
|
4862
|
+
if (modal) return modal
|
|
4863
|
+
modal = document.createElement('div')
|
|
4864
|
+
modal.id = 'modal-workspace-admin'
|
|
4865
|
+
modal.className = 'modal hidden'
|
|
4866
|
+
modal.setAttribute('role', 'dialog')
|
|
4867
|
+
modal.setAttribute('aria-modal', 'true')
|
|
4868
|
+
modal.setAttribute('aria-labelledby', 'workspace-admin-title')
|
|
4869
|
+
modal.innerHTML = `<div class="modal-card"><div id="workspace-admin-title" class="modal-title"></div><div class="modal-body" id="workspace-admin-host"></div><div class="modal-actions"><button type="button" class="btn subtle" data-workspace-admin-close></button></div></div>`
|
|
4870
|
+
document.body.append(modal)
|
|
4871
|
+
const close = () => modal.classList.add('hidden')
|
|
4872
|
+
modal.addEventListener('click', event => {
|
|
4873
|
+
if (event.target === modal || event.target.closest('[data-workspace-admin-close]')) close()
|
|
4874
|
+
})
|
|
4875
|
+
modal.querySelector('[data-workspace-admin-close]').textContent = t('modal.close')
|
|
4876
|
+
modal.querySelector('#workspace-admin-title').textContent = t('workspace.manage')
|
|
4877
|
+
return modal
|
|
4878
|
+
}
|
|
4879
|
+
|
|
4880
|
+
function openWorkspaceAdmin() {
|
|
4881
|
+
if (!sessionManager) return
|
|
4882
|
+
const modal = ensureWorkspaceAdminModal()
|
|
4883
|
+
sessionManager.hydrate()
|
|
4884
|
+
if (!workspaceAdminMount) {
|
|
4885
|
+
workspaceAdminMount = window.DshSessionManagement.mountWorkspaceAdmin($('workspace-admin-host'), sessionManager, {
|
|
4886
|
+
promptTitle: promptWorkspaceTitle,
|
|
4887
|
+
onResult: result => { if (result?.ok) { renderSessions(); workspaceAdminMount?.refresh() } },
|
|
4888
|
+
})
|
|
4889
|
+
} else workspaceAdminMount.refresh()
|
|
4890
|
+
modal.querySelector('#workspace-admin-title').textContent = t('workspace.manage')
|
|
4891
|
+
modal.querySelector('[data-workspace-admin-close]').textContent = t('modal.close')
|
|
4892
|
+
modal.classList.remove('hidden')
|
|
4893
|
+
}
|
|
4894
|
+
|
|
4895
|
+
function refreshSessionAdminActions() {
|
|
4896
|
+
const box = $('session-admin-actions')
|
|
4897
|
+
const session = state.byId.get(state.current)
|
|
4898
|
+
if (!box || !sessionManager || !session) return
|
|
4899
|
+
box.innerHTML = window.DshSessionManagement.renderSessionAdminActions(session, sessionManager.getState())
|
|
4900
|
+
}
|
|
4901
|
+
|
|
4902
|
+
async function unarchiveSessionFromList(sessionId) {
|
|
4903
|
+
if (!sessionManager) return
|
|
4904
|
+
await sessionManager.unarchive(sessionId)
|
|
4905
|
+
renderSessions()
|
|
4906
|
+
}
|
|
4907
|
+
|
|
4908
|
+
function updateBcControlLabels() {
|
|
4909
|
+
const manage = $('btn-manage-workspaces')
|
|
4910
|
+
if (manage) manage.textContent = t('workspace.manage')
|
|
4911
|
+
if (quoteSelectionButton) quoteSelectionButton.textContent = t('composer.quoteSelection')
|
|
4912
|
+
const modal = $('modal-workspace-admin')
|
|
4913
|
+
if (modal) {
|
|
4914
|
+
modal.querySelector('#workspace-admin-title').textContent = t('workspace.manage')
|
|
4915
|
+
modal.querySelector('[data-workspace-admin-close]').textContent = t('modal.close')
|
|
4916
|
+
}
|
|
4917
|
+
}
|
|
4918
|
+
|
|
4919
|
+
function initBcFeatures() {
|
|
4920
|
+
initComposerToolsUi()
|
|
4921
|
+
initSessionSearchUi()
|
|
4922
|
+
initSessionManagementUi()
|
|
4923
|
+
initReviewFeatures()
|
|
4924
|
+
syncComposerToolsScope()
|
|
4925
|
+
}
|
|
4926
|
+
|
|
4927
|
+
function isPlanReviewQuestion(question) {
|
|
4928
|
+
return !!window.DshPlanReview?.planReviewOf?.(question?.questions)
|
|
4929
|
+
}
|
|
4930
|
+
|
|
4931
|
+
function planReviewSnapshot(sessionId) {
|
|
4932
|
+
const session = state.byId.get(sessionId)
|
|
4933
|
+
const plan = session?.projections?.values?.plan
|
|
4934
|
+
return {
|
|
4935
|
+
plan,
|
|
4936
|
+
questions: (state.questions || []).filter(frame => String(frame?.sessionId || '') === String(sessionId || '')),
|
|
4937
|
+
connected: !!state.streamsOk?.mux,
|
|
4938
|
+
readOnly: false,
|
|
4939
|
+
capability: plan === undefined ? undefined : true,
|
|
4940
|
+
}
|
|
4941
|
+
}
|
|
4942
|
+
|
|
4943
|
+
function updatePlanReviewVisibility(view) {
|
|
4944
|
+
if (!planReviewHost) return
|
|
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))
|
|
4950
|
+
planReviewHost.classList.toggle('hidden', !visible)
|
|
4951
|
+
}
|
|
4952
|
+
|
|
4953
|
+
function refreshPlanReview() {
|
|
4954
|
+
if (!planReviewController) return
|
|
4955
|
+
let view = null
|
|
4956
|
+
try { view = planReviewController.render() } catch {}
|
|
4957
|
+
updatePlanReviewVisibility(view)
|
|
4958
|
+
return view
|
|
4959
|
+
}
|
|
4960
|
+
|
|
4961
|
+
function turnDiffEnabled() {
|
|
4962
|
+
return LS.get('turnDiffEnabled', '0') === '1'
|
|
4963
|
+
}
|
|
4964
|
+
|
|
4965
|
+
function turnDiffHtmlFor(entry) {
|
|
4966
|
+
if (!turnDiffController || !turnDiffController.isEnabled()) return ''
|
|
4967
|
+
if (entry?.event?.type !== 'turn/end') return ''
|
|
4968
|
+
const turnNumber = Number(entry.event?.data?.turn)
|
|
4969
|
+
if (!Number.isSafeInteger(turnNumber) || turnNumber < 1) return ''
|
|
4970
|
+
const full = turnDiffController.view()
|
|
4971
|
+
const turns = full.turns.filter(turn => turn.turn === turnNumber)
|
|
4972
|
+
if (!turns.length) return ''
|
|
4973
|
+
return `<div class="dr-diff-turn-slot" data-turn="${turnNumber}">${window.DshTurnDiff.viewHtml({ ...full, turns })}</div>`
|
|
4974
|
+
}
|
|
4975
|
+
|
|
4976
|
+
async function fetchHostChangesJson(path, query) {
|
|
4977
|
+
const url = new URL(apiUrl(path), location.href)
|
|
4978
|
+
for (const [key, value] of Object.entries(query || {})) url.searchParams.set(key, String(value))
|
|
4979
|
+
const res = await fetch(url.href, {
|
|
4980
|
+
headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
|
|
4981
|
+
cache: 'no-store',
|
|
4982
|
+
signal: AbortSignal.timeout(45000),
|
|
4983
|
+
})
|
|
4984
|
+
if (res.status === 401) authFailure()
|
|
4985
|
+
let data = null
|
|
4986
|
+
try { data = await res.json() } catch {}
|
|
4987
|
+
return { ok: res.ok, status: res.status, data }
|
|
4988
|
+
}
|
|
4989
|
+
|
|
4990
|
+
let turnDiffActionsBound = false
|
|
4991
|
+
function bindTurnDiffActions() {
|
|
4992
|
+
if (turnDiffActionsBound || !turnDiffController) return
|
|
4993
|
+
const container = $('history')
|
|
4994
|
+
if (!container) return
|
|
4995
|
+
turnDiffActionsBound = true
|
|
4996
|
+
container.addEventListener('click', event => {
|
|
4997
|
+
const button = event.target?.closest?.('[data-dr-diff-action]')
|
|
4998
|
+
if (!button || button.disabled) return
|
|
4999
|
+
const action = button.dataset?.drDiffAction || ''
|
|
5000
|
+
const turn = Number(button.dataset?.drDiffTurn)
|
|
5001
|
+
const index = Number(button.dataset?.drDiffFile)
|
|
5002
|
+
const delivery = Number(button.dataset?.drDiffDelivery)
|
|
5003
|
+
const run = {
|
|
5004
|
+
toggle: () => turnDiffController.toggleTurn(turn),
|
|
5005
|
+
file: () => turnDiffController.selectFile(turn, index),
|
|
5006
|
+
delivery: () => { turnDiffController.openDelivery(turn, delivery); return true },
|
|
5007
|
+
'retry-summary': () => turnDiffController.retrySummary(turn),
|
|
5008
|
+
'retry-diff': () => turnDiffController.retryDiff(turn, index),
|
|
5009
|
+
}[action]
|
|
5010
|
+
if (!run) return
|
|
5011
|
+
const finish = () => { if (state.current) renderHistory(false, 'keep') }
|
|
5012
|
+
try {
|
|
5013
|
+
const result = run()
|
|
5014
|
+
if (result && typeof result.then === 'function') result.then(finish, finish)
|
|
5015
|
+
else finish()
|
|
5016
|
+
} catch { finish() }
|
|
5017
|
+
})
|
|
5018
|
+
}
|
|
5019
|
+
|
|
5020
|
+
function initReviewFeatures() {
|
|
5021
|
+
if (window.DshPlanReview && !planReviewController) {
|
|
5022
|
+
const anchor = $('session-cards')
|
|
5023
|
+
if (anchor) {
|
|
5024
|
+
planReviewHost = document.createElement('section')
|
|
5025
|
+
planReviewHost.id = 'plan-review-host'
|
|
5026
|
+
planReviewHost.className = 'plan-review-host hidden'
|
|
5027
|
+
planReviewHost.setAttribute('aria-live', 'polite')
|
|
5028
|
+
anchor.after(planReviewHost)
|
|
5029
|
+
planReviewController = window.DshPlanReview.create({
|
|
5030
|
+
command: async line => ({ executed: await runSlashCommand(line, true) }),
|
|
5031
|
+
respond: (rpcId, value) => respond(rpcId, value),
|
|
5032
|
+
state: {
|
|
5033
|
+
sessionId: () => state.current,
|
|
5034
|
+
snapshot: sessionId => planReviewSnapshot(sessionId),
|
|
5035
|
+
entries: sessionId => state.current === sessionId ? state.history.visible : [],
|
|
5036
|
+
},
|
|
5037
|
+
dom: { root: planReviewHost },
|
|
5038
|
+
onOpenPlan: () => {},
|
|
5039
|
+
notify: (message, kind) => { if (message) toast(message, kind === 'err' ? 'err' : '') },
|
|
5040
|
+
})
|
|
5041
|
+
updatePlanReviewVisibility(planReviewController.view())
|
|
5042
|
+
}
|
|
5043
|
+
}
|
|
5044
|
+
if (window.DshTurnDiff && !turnDiffController) {
|
|
5045
|
+
turnDiffRoot = document.createElement('div')
|
|
5046
|
+
turnDiffRoot.hidden = true
|
|
5047
|
+
turnDiffController = window.DshTurnDiff.create({
|
|
5048
|
+
state: {
|
|
5049
|
+
sessionId: () => state.current,
|
|
5050
|
+
entries: sessionId => state.current === sessionId ? state.history.visible : [],
|
|
5051
|
+
},
|
|
5052
|
+
fetchJson: fetchHostChangesJson,
|
|
5053
|
+
dom: { root: turnDiffRoot },
|
|
5054
|
+
layout: 'mobile',
|
|
5055
|
+
enabled: turnDiffEnabled,
|
|
5056
|
+
onOpenFile: ({ path }) => {
|
|
5057
|
+
const name = String(path || '').split(/[\\/]/).pop() || ''
|
|
5058
|
+
if (path && name) openFsPreview(path, name)
|
|
5059
|
+
},
|
|
5060
|
+
notify: (message, kind) => { if (message) toast(message, kind === 'err' ? 'err' : '') },
|
|
5061
|
+
})
|
|
5062
|
+
turnDiffController.setEnabled(turnDiffEnabled())
|
|
5063
|
+
bindTurnDiffActions()
|
|
5064
|
+
}
|
|
5065
|
+
initTurnDiffSetting()
|
|
5066
|
+
}
|
|
5067
|
+
|
|
5068
|
+
function initTurnDiffSetting() {
|
|
5069
|
+
const page = $('settings-page-general')
|
|
5070
|
+
if (!page || $('opt-turn-diff')) return
|
|
5071
|
+
// The optional Workflow shell restructures this page after boot; attach to
|
|
5072
|
+
// its stable card when present, else to the static group/page for plain UI.
|
|
5073
|
+
const group = page.querySelector('[data-workflow-settings-slot="input"]')
|
|
5074
|
+
|| page.querySelector('[data-workflow-settings-slot]')
|
|
5075
|
+
|| page.querySelector('.settings-group:last-child')
|
|
5076
|
+
|| page
|
|
5077
|
+
const row = document.createElement('div')
|
|
5078
|
+
row.className = 'setting-row'
|
|
5079
|
+
row.innerHTML = `<div><div class="setting-name"></div><div class="setting-desc"></div></div><label class="switch"><input type="checkbox" id="opt-turn-diff"><span class="slider"></span></label>`
|
|
5080
|
+
row.querySelector('.setting-name').textContent = t('settings.turnDiffTitle')
|
|
5081
|
+
row.querySelector('.setting-desc').textContent = t('settings.turnDiffDesc')
|
|
5082
|
+
group.append(row)
|
|
5083
|
+
const checkbox = row.querySelector('#opt-turn-diff')
|
|
5084
|
+
checkbox.checked = turnDiffEnabled()
|
|
5085
|
+
checkbox.addEventListener('change', () => {
|
|
5086
|
+
LS.set('turnDiffEnabled', checkbox.checked ? '1' : '0')
|
|
5087
|
+
turnDiffController?.setEnabled(checkbox.checked)
|
|
5088
|
+
if (state.current) renderHistory(false, 'keep')
|
|
5089
|
+
})
|
|
5090
|
+
}
|
|
5091
|
+
|
|
5092
|
+
function updateTurnDiffSettingLabel() {
|
|
5093
|
+
const row = $('opt-turn-diff')?.closest('.setting-row')
|
|
5094
|
+
if (!row) return
|
|
5095
|
+
const name = row.querySelector('.setting-name')
|
|
5096
|
+
const desc = row.querySelector('.setting-desc')
|
|
5097
|
+
if (name) name.textContent = t('settings.turnDiffTitle')
|
|
5098
|
+
if (desc) desc.textContent = t('settings.turnDiffDesc')
|
|
5099
|
+
}
|
|
5100
|
+
|
|
3928
5101
|
// 主机拥有权限模式(沙箱+审批捆绑)与可选目录;Remote 只按主机返回渲染,
|
|
3929
5102
|
// 不为未安装或不存在的预设造选项。旧主机没有该目录时回退三种沙箱模式。
|
|
3930
5103
|
// 目录直接作为“指令”列表中的权限模式行显示,Auto review 可用时同样出现在这里。
|
|
@@ -4139,11 +5312,16 @@ function loadSessionPresets(prefix) {
|
|
|
4139
5312
|
}
|
|
4140
5313
|
async function newSession(preferredWorkspace = '') {
|
|
4141
5314
|
if (!state.token) { showView('view-settings'); return }
|
|
5315
|
+
const connection = captureConnection()
|
|
5316
|
+
if (await prepareNewSessionForm(preferredWorkspace, connection.valid)) $('modal-new-session').classList.remove('hidden')
|
|
5317
|
+
}
|
|
5318
|
+
async function prepareNewSessionForm(preferredWorkspace, current) {
|
|
4142
5319
|
if (!workspaceItems().length) await refreshWorkbench()
|
|
5320
|
+
if (!current()) return false
|
|
4143
5321
|
const preferred = typeof preferredWorkspace === 'string' && preferredWorkspace || workspaceById(state.workspaceFilter)?.workspaceId || LS.get('lastNewSessionWorkspaceV1', '')
|
|
4144
5322
|
renderNewSessionWorkspace(preferred)
|
|
4145
5323
|
void loadSessionPresets('new-session')
|
|
4146
|
-
|
|
5324
|
+
return true
|
|
4147
5325
|
}
|
|
4148
5326
|
function renderNewSessionWorkspace(preferredId = '') {
|
|
4149
5327
|
const items = workspaceItems()
|
|
@@ -4160,6 +5338,7 @@ function renderNewSessionWorkspace(preferredId = '') {
|
|
|
4160
5338
|
$('new-session-create').disabled = !workspace
|
|
4161
5339
|
}
|
|
4162
5340
|
function closeNewSessionModal() {
|
|
5341
|
+
if (isGroupDrawerPanel('new')) { setGroupDrawerPanel(''); return }
|
|
4163
5342
|
$('modal-new-session').classList.add('hidden')
|
|
4164
5343
|
}
|
|
4165
5344
|
async function createSessionInWorkspace() {
|
|
@@ -4294,21 +5473,10 @@ function repairMissingStreams() {
|
|
|
4294
5473
|
}
|
|
4295
5474
|
}
|
|
4296
5475
|
async function probeOverviewLinks(signal) {
|
|
4297
|
-
const connection=captureConnection()
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
|
|
4301
|
-
timer=setTimeout(cancel,6500)
|
|
4302
|
-
const healthRequest=fetch(base+'/health?probe=fresh&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
|
|
4303
|
-
if(!response.ok)throw Error('health')
|
|
4304
|
-
const health=await response.json();if(health?.ok!==true)throw Error('health')
|
|
4305
|
-
return health
|
|
4306
|
-
}).catch(()=>null).finally(()=>{clearTimeout(timer);signal.removeEventListener('abort',cancel)})
|
|
4307
|
-
const [health,host]=await Promise.all([healthRequest,refreshHostDescription()])
|
|
4308
|
-
if(!connection.valid()||signal.aborted)throw Error('stale check')
|
|
4309
|
-
if(health){state.gatewayHealth[base]=health}
|
|
4310
|
-
else delete state.gatewayHealth[base]
|
|
4311
|
-
return {gateway:!!health}
|
|
5476
|
+
const connection = captureConnection()
|
|
5477
|
+
const [health] = await Promise.all([refreshConnectionHealth(), refreshHostDescription()])
|
|
5478
|
+
if (!connection.valid() || signal.aborted) throw Error('stale check')
|
|
5479
|
+
return { gateway: !!health }
|
|
4312
5480
|
}
|
|
4313
5481
|
function startOverviewDetection(force=false,identityChanged=false) {
|
|
4314
5482
|
if(identityChanged)overviewDetector?.pause()
|
|
@@ -4410,7 +5578,8 @@ function renderOverview() {
|
|
|
4410
5578
|
$('overview-dsh-version').textContent = state.hostInfo?.version || '—'
|
|
4411
5579
|
$('overview-gateway-version').textContent = checks.gateway ? t('overview.online') : t('overview.offlineShort')
|
|
4412
5580
|
$('overview-active-sessions').textContent = String(running)
|
|
4413
|
-
|
|
5581
|
+
const connectionStatus = mobileConnectionStatus()
|
|
5582
|
+
$('overview-connection-mode').textContent = t(connectionStatus === 'conn.on' ? 'overview.ws' : connectionStatus)
|
|
4414
5583
|
$('overview-active-count').textContent = running ? t('overview.activeCount', { n: running }) : ''
|
|
4415
5584
|
$('overview-session-list').innerHTML = sessions.length ? sessions.map(s => `<button type="button" class="overview-session-item ${s.running ? 'running' : ''}" data-overview-session="${esc(s.sessionId)}">
|
|
4416
5585
|
<span class="overview-item-mark">${s.running ? '●' : '○'}</span><span class="overview-item-copy"><span class="overview-item-title">${esc(sessionLabelOf(s))}</span><span class="overview-item-desc">${s.running ? esc(t('sessions.running')) + ' · ' : ''}${esc(fmtTime(sessionSortTime(s)))}</span></span><span class="overview-item-arrow">›</span>
|
|
@@ -4507,6 +5676,7 @@ function renderPending() {
|
|
|
4507
5676
|
btn.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === btn.dataset.question))))
|
|
4508
5677
|
renderSessionPending()
|
|
4509
5678
|
updatePendingBadge()
|
|
5679
|
+
renderGroupDrawerOperations()
|
|
4510
5680
|
renderOverview()
|
|
4511
5681
|
}
|
|
4512
5682
|
|
|
@@ -4605,6 +5775,11 @@ function fitQuestionViewport() {
|
|
|
4605
5775
|
|
|
4606
5776
|
function openQuestionModal(q) {
|
|
4607
5777
|
if (!q) return
|
|
5778
|
+
if (typeof isPlanReviewQuestion === 'function' && isPlanReviewQuestion(q)) {
|
|
5779
|
+
if (typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
5780
|
+
if (typeof planReviewHost !== 'undefined') planReviewHost?.scrollIntoView?.({ behavior: 'smooth', block: 'center' })
|
|
5781
|
+
return
|
|
5782
|
+
}
|
|
4608
5783
|
state.questionModal = q
|
|
4609
5784
|
$('question-body').innerHTML = q.questions.map((item, i) => `
|
|
4610
5785
|
<div class="q-item">
|
|
@@ -4660,49 +5835,36 @@ async function submitQuestion() {
|
|
|
4660
5835
|
}
|
|
4661
5836
|
|
|
4662
5837
|
/* ---------------- 后台任务 ---------------- */
|
|
4663
|
-
|
|
4664
|
-
|
|
4665
|
-
|
|
4666
|
-
|
|
4667
|
-
|
|
4668
|
-
|
|
4669
|
-
|
|
4670
|
-
|
|
4671
|
-
|
|
4672
|
-
|
|
4673
|
-
|
|
4674
|
-
|
|
4675
|
-
|
|
4676
|
-
|
|
4677
|
-
|
|
4678
|
-
|
|
4679
|
-
|
|
4680
|
-
|
|
4681
|
-
|
|
4682
|
-
|
|
4683
|
-
}
|
|
4684
|
-
}
|
|
5838
|
+
const hostAccess = connection => window.DshHostQueue.readAccess(connection, apiUrl)
|
|
5839
|
+
const hostQueue = window.DshHostQueue?.create({ rpc, access: hostAccess, capture: captureConnection, box: () => $('queue-dock'),
|
|
5840
|
+
session: () => state.current, items: () => state.queues[state.current], running: () => !!state.byId.get(state.current)?.running,
|
|
5841
|
+
apply(sessionId, snapshot) {
|
|
5842
|
+
state.queues[sessionId] = snapshot.items
|
|
5843
|
+
const session = state.byId.get(sessionId)
|
|
5844
|
+
if (session) session.running = snapshot.running
|
|
5845
|
+
},
|
|
5846
|
+
})
|
|
5847
|
+
const hostSchedule = window.DshHostSchedule?.create({ rpc, access: hostAccess, capture: captureConnection, box: () => $('view-schedule'),
|
|
5848
|
+
workspaces: workspaceItems,
|
|
5849
|
+
sessions: () => state.sessions.filter(row => row.origin !== 'subagent' && !(state.wbArchived || []).includes(row.sessionId)).map(row => ({ id: row.sessionId, label: titleOf(row) })),
|
|
5850
|
+
async openSession(id) {
|
|
5851
|
+
const connection = captureConnection()
|
|
5852
|
+
await refreshSessions()
|
|
5853
|
+
if (!connection.valid()) return
|
|
5854
|
+
if (!state.byId.has(id)) return toast(t('session.unknown'), 'err')
|
|
5855
|
+
await openSession(id)
|
|
5856
|
+
},
|
|
5857
|
+
})
|
|
4685
5858
|
function renderQueue() {
|
|
4686
5859
|
renderComposerSend()
|
|
5860
|
+
hostQueue?.render()
|
|
4687
5861
|
const s = state.byId.get(state.current)
|
|
4688
5862
|
if (!s) return
|
|
4689
5863
|
const items = (state.queues[state.current] || []).filter(item => item?.placement === 'queued')
|
|
4690
|
-
const box = $('queue-dock')
|
|
4691
|
-
if (box) {
|
|
4692
|
-
box.classList.toggle('hidden', !items.length)
|
|
4693
|
-
box.innerHTML = items.length ? `<div class="queue-dock-head"><span>⌁</span><span>${esc(t('queue.title'))} · ${items.length}</span></div><div class="queue-dock-list">${items.map(item => {
|
|
4694
|
-
const key = `${state.current}:${item.id}`
|
|
4695
|
-
const busy = !!state.queueSteering[key]
|
|
4696
|
-
return `<div class="queue-dock-item"><span class="queue-dock-preview" title="${esc(queuePreview(item))}">${esc(queuePreview(item))}</span><button type="button" class="mini-btn queue-dock-action" data-queue-steer="${esc(item.id)}" title="${esc(s.running ? t('queue.steer') : t('queue.steerUnavailable'))}" ${s.running && !busy ? '' : 'disabled'}>${busy ? '…' : esc(t('queue.steer'))}</button></div>`
|
|
4697
|
-
}).join('')}</div>` : ''
|
|
4698
|
-
box.querySelectorAll('[data-queue-steer]').forEach(button => {
|
|
4699
|
-
button.addEventListener('click', () => steerQueueItem(button.dataset.queueSteer))
|
|
4700
|
-
})
|
|
4701
|
-
}
|
|
4702
5864
|
updateCancelBtn()
|
|
4703
5865
|
updateSessionStatus()
|
|
4704
5866
|
// 队列数量在会话列表已显示; 详情页不重复大 UI
|
|
4705
|
-
$('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 })
|
|
4706
5868
|
renderSessions()
|
|
4707
5869
|
}
|
|
4708
5870
|
|
|
@@ -4927,6 +6089,11 @@ async function chatImageAttachment(attachment, sessionId) {
|
|
|
4927
6089
|
...(ref.height === undefined ? {} : { height: ref.height }),
|
|
4928
6090
|
...(ref.name ? { name: ref.name } : {}),
|
|
4929
6091
|
} }
|
|
6092
|
+
const session = state.byId?.get(sessionId)
|
|
6093
|
+
if (session?.origin === 'subagent' && session.parentSessionId) {
|
|
6094
|
+
payload.parentSessionId = session.parentSessionId
|
|
6095
|
+
payload.subagentMode = session.subagentMode || 'unknown'
|
|
6096
|
+
}
|
|
4930
6097
|
const result = await rpc('session.attachment', payload, 120000)
|
|
4931
6098
|
if (!connection.valid() || state.current !== sessionId) throw new Error('stale image')
|
|
4932
6099
|
return result
|
|
@@ -5604,14 +6771,20 @@ async function maybeWarnAppBehindGateway({ probe = false } = {}) {
|
|
|
5604
6771
|
function closeAppVersionWarning(checkNow = false) {
|
|
5605
6772
|
$('modal-app-version-warning').classList.add('hidden')
|
|
5606
6773
|
if (checkNow) {
|
|
5607
|
-
|
|
5608
|
-
showSettingsPage('about')
|
|
5609
|
-
void checkUpdate(false)
|
|
6774
|
+
openUpdateSettings()
|
|
5610
6775
|
} else {
|
|
5611
6776
|
scheduleStartupNotices(150)
|
|
5612
6777
|
}
|
|
5613
6778
|
}
|
|
5614
6779
|
|
|
6780
|
+
function openUpdateSettings() {
|
|
6781
|
+
showView('view-settings')
|
|
6782
|
+
showSettingsPage('about')
|
|
6783
|
+
$('settings-update-row')?.scrollIntoView({ block: 'start' })
|
|
6784
|
+
$('btn-check-update')?.focus({ preventScroll: true })
|
|
6785
|
+
void checkUpdate(false)
|
|
6786
|
+
}
|
|
6787
|
+
|
|
5615
6788
|
function resetUpdateExpand() {
|
|
5616
6789
|
const desc = $('update-desc')
|
|
5617
6790
|
if (desc) desc.classList.remove('expanded')
|
|
@@ -5631,14 +6804,35 @@ function toggleUpdateExpand() {
|
|
|
5631
6804
|
}
|
|
5632
6805
|
|
|
5633
6806
|
async function loadLocalVersion() {
|
|
5634
|
-
|
|
5635
|
-
|
|
5636
|
-
|
|
5637
|
-
|
|
5638
|
-
|
|
5639
|
-
|
|
5640
|
-
|
|
5641
|
-
|
|
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 }
|
|
5642
6836
|
}
|
|
5643
6837
|
|
|
5644
6838
|
/* ---------------- 远程公告 ----------------
|
|
@@ -7318,6 +8512,7 @@ async function openModelConfigDocument() {
|
|
|
7318
8512
|
}
|
|
7319
8513
|
/* ---------------- 视图切换 ---------------- */
|
|
7320
8514
|
function showView(id, pluginRoute = 'manage') {
|
|
8515
|
+
if (groupDrawerOpen()) closeGroupDrawer({ restoreFocus: false })
|
|
7321
8516
|
window.DshSlashSuggestions?.close()
|
|
7322
8517
|
window.DshExtensions?.closeShortcuts()
|
|
7323
8518
|
if (id !== 'view-session') window.DshSubagents?.close()
|
|
@@ -7326,7 +8521,10 @@ function showView(id, pluginRoute = 'manage') {
|
|
|
7326
8521
|
if (window.DshWorkflow?.isMounted() && id === 'view-activity') id = 'view-home'
|
|
7327
8522
|
if (id !== 'view-session') conversationView?.pause()
|
|
7328
8523
|
if (id !== 'view-session' && document.body.classList.contains('in-session') && state.current) void archiveEmptySessionOnLeave(state.current)
|
|
7329
|
-
|
|
8524
|
+
const leavingSchedule = id !== 'view-schedule' && !$('view-schedule').classList.contains('hidden')
|
|
8525
|
+
for (const v of ['view-home', 'view-files', 'view-session', 'view-activity', 'view-plugins', 'view-settings', 'view-schedule']) $(v).classList.toggle('hidden', v !== id)
|
|
8526
|
+
if (leavingSchedule) hostSchedule?.leave()
|
|
8527
|
+
if (id === 'view-schedule') void hostSchedule?.refresh(true)
|
|
7330
8528
|
// 离开会话页必须清掉 in-session, 否则其他页面顶栏被 body 样式隐藏
|
|
7331
8529
|
document.body.classList.toggle('in-session', id === 'view-session')
|
|
7332
8530
|
window.DshFileInbox?.render()
|
|
@@ -7334,7 +8532,8 @@ function showView(id, pluginRoute = 'manage') {
|
|
|
7334
8532
|
if (id === 'view-session') conversationView?.resume()
|
|
7335
8533
|
$('session-actions')?.close()
|
|
7336
8534
|
$('session-info')?.close()
|
|
7337
|
-
|
|
8535
|
+
const navView = id === 'view-schedule' ? 'view-settings' : id
|
|
8536
|
+
document.querySelectorAll('.nav-btn').forEach(b => b.classList.toggle('active', b.dataset.view === navView))
|
|
7338
8537
|
window.DshMotion?.view($(id))
|
|
7339
8538
|
window.scrollTo(0, 0)
|
|
7340
8539
|
if (id === 'view-files' && !state.fs.loaded) {
|
|
@@ -7347,7 +8546,7 @@ function showView(id, pluginRoute = 'manage') {
|
|
|
7347
8546
|
if(id==='view-activity')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}
|
|
7348
8547
|
}
|
|
7349
8548
|
|
|
7350
|
-
const SETTINGS_GROUPS = ['general', 'model', 'tests', 'servers', 'notify', 'theme', 'about']
|
|
8549
|
+
const SETTINGS_GROUPS = ['general', 'model', 'tests', 'servers', 'cloud-relay', 'notify', 'theme', 'about']
|
|
7351
8550
|
function showSettingsHome() {
|
|
7352
8551
|
const home = $('settings-home')
|
|
7353
8552
|
if (!home) return
|
|
@@ -7360,8 +8559,30 @@ function showSettingsPage(name) {
|
|
|
7360
8559
|
if (!home || !SETTINGS_GROUPS.includes(name)) return
|
|
7361
8560
|
home.classList.add('hidden')
|
|
7362
8561
|
for (const g of SETTINGS_GROUPS) $('settings-page-' + g)?.classList.toggle('hidden', g !== name)
|
|
8562
|
+
if (name === 'servers') {
|
|
8563
|
+
const openSections = $('settings-page-servers')?.querySelectorAll('.workflow-settings-disclosure[open]')
|
|
8564
|
+
openSections?.forEach(section => { section.open = false })
|
|
8565
|
+
}
|
|
7363
8566
|
window.scrollTo(0, 0)
|
|
7364
8567
|
if (name === 'model') void loadModelSettings()
|
|
8568
|
+
if (name === 'general' && typeof initTurnDiffSetting === 'function') initTurnDiffSetting()
|
|
8569
|
+
}
|
|
8570
|
+
|
|
8571
|
+
function mobileConnectionStatus() {
|
|
8572
|
+
const issue = activeConnectionIssue()
|
|
8573
|
+
if (issue) return issue === 426 ? 'conn.pairingRequired' : 'conn.authFailed'
|
|
8574
|
+
if (!navigator.onLine) return 'conn.offline'
|
|
8575
|
+
if (!state.token) return 'conn.off'
|
|
8576
|
+
const health = currentConnectionHealth()
|
|
8577
|
+
if (health === undefined) return 'conn.checking'
|
|
8578
|
+
if (health === null) return 'conn.gatewayOffline'
|
|
8579
|
+
const upstream = health.upstreamOk ?? health.upstreamReachable
|
|
8580
|
+
if (upstream === false) return 'conn.dshOffline'
|
|
8581
|
+
if (upstream !== true && (!state.hostInfo || state.hostInfo.metadataOnly === true)) return 'conn.checking'
|
|
8582
|
+
if (state.streamMode === 'poll' && state.pollSeq.muxReady) return 'conn.poll'
|
|
8583
|
+
if (state.streamMode === 'ws' && state.streamsOk?.mux && health.events?.mux?.connected !== false) return 'conn.on'
|
|
8584
|
+
if (reconnectInfo) return 'conn.reconnecting'
|
|
8585
|
+
return state.errCount > 0 ? 'conn.failed' : 'conn.checking'
|
|
7365
8586
|
}
|
|
7366
8587
|
|
|
7367
8588
|
function updateConn() {
|
|
@@ -7374,36 +8595,17 @@ function updateConn() {
|
|
|
7374
8595
|
const ms = cur ? state.serverLatency[serverKey(cur)] : undefined
|
|
7375
8596
|
const curGroup = cur ? cur.group : state.activeGroup
|
|
7376
8597
|
const curLabel = cur ? (cur.note || cur.url) : (state.server || t('speed.origin'))
|
|
7377
|
-
const
|
|
7378
|
-
|
|
7379
|
-
|
|
7380
|
-
|
|
7381
|
-
|
|
7382
|
-
|
|
7383
|
-
|
|
7384
|
-
|
|
7385
|
-
|
|
7386
|
-
|
|
7387
|
-
|
|
7388
|
-
return
|
|
7389
|
-
}
|
|
7390
|
-
const ok = !!state.streamsOk?.mux
|
|
7391
|
-
if (!ok && reconnectInfo) {
|
|
7392
|
-
const remain = Math.max(0, Math.ceil((reconnectInfo.at - Date.now()) / 1000))
|
|
7393
|
-
el.textContent = remain > 0 ? t('conn.reconnectIn', { n: remain }) : t('conn.reconnecting')
|
|
7394
|
-
el.className = 'topbar-btn conn-badge off'
|
|
7395
|
-
el.title = t('conn.reconnecting') + ' · ' + titleBase
|
|
7396
|
-
return
|
|
7397
|
-
}
|
|
7398
|
-
if (!ok && state.errCount > 0) {
|
|
7399
|
-
el.textContent = t('conn.failed')
|
|
7400
|
-
el.className = 'topbar-btn conn-badge off'
|
|
7401
|
-
el.title = titleBase
|
|
7402
|
-
return
|
|
7403
|
-
}
|
|
7404
|
-
el.textContent = ok ? t('conn.on') : t('conn.off')
|
|
7405
|
-
el.className = 'topbar-btn conn-badge ' + (ok ? 'on' : 'off')
|
|
7406
|
-
el.title = titleBase
|
|
8598
|
+
const actionTitle = window.DshWorkflow?.isMounted() ? 'conn.details' : 'conn.refresh'
|
|
8599
|
+
const titleBase = t('conn.titleGroup', { group: curGroup, url: curLabel, ms: Number.isFinite(ms) ? ms + 'ms' : '—' }) + ' · ' + t(actionTitle)
|
|
8600
|
+
const issue = activeConnectionIssue()
|
|
8601
|
+
const hint = $(el.getAttribute('aria-describedby'))
|
|
8602
|
+
if (hint) hint.textContent = t(issue ? 'conn.troubleshoot' : hint.dataset.i18n)
|
|
8603
|
+
const status = mobileConnectionStatus()
|
|
8604
|
+
const remain = status === 'conn.reconnecting' ? Math.ceil((reconnectInfo.at - Date.now()) / 1000) : 0
|
|
8605
|
+
el.textContent = remain > 0 ? t('conn.reconnectIn', { n: remain }) : t(status)
|
|
8606
|
+
el.className = 'topbar-btn conn-badge ' + (status === 'conn.on' ? 'on' : 'off')
|
|
8607
|
+
const statusTitle = issue ? t('conn.troubleshoot') : status === 'conn.poll' ? t('conn.pollTitle') : ''
|
|
8608
|
+
el.title = statusTitle ? statusTitle + ' · ' + titleBase : titleBase
|
|
7407
8609
|
}
|
|
7408
8610
|
|
|
7409
8611
|
function autosize(el) {
|
|
@@ -7515,6 +8717,8 @@ function applyPairUrl(url, options = {}) {
|
|
|
7515
8717
|
state.servers.unshift({ id: newServerId(), url: server, note: '', group: state.activeGroup, token: tok })
|
|
7516
8718
|
}
|
|
7517
8719
|
}
|
|
8720
|
+
// Pairing carries one credential for every address it lists.
|
|
8721
|
+
syncGroupToken(state.activeGroup, tok)
|
|
7518
8722
|
const first = state.servers.find(s => s.url === servers[0] && normalizedServerToken(s.token) === tok)
|
|
7519
8723
|
if (!first) return false
|
|
7520
8724
|
if (previousServer !== first.url || previousToken !== tok) resetFsForServer()
|
|
@@ -7527,10 +8731,10 @@ function applyPairUrl(url, options = {}) {
|
|
|
7527
8731
|
$('token-desc').textContent = t('token.savedScan')
|
|
7528
8732
|
syncBgConfig()
|
|
7529
8733
|
const setupId = u.searchParams.get('relaySetup')
|
|
7530
|
-
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) {
|
|
7531
8735
|
relaySetup = { id: setupId, token: tok, servers }
|
|
7532
8736
|
showView('view-settings')
|
|
7533
|
-
showSettingsPage('
|
|
8737
|
+
showSettingsPage('cloud-relay')
|
|
7534
8738
|
requestAnimationFrame(() => {
|
|
7535
8739
|
$('relay-phone-pairing')?.scrollIntoView({ block: 'start' })
|
|
7536
8740
|
const connection = captureConnection()
|
|
@@ -7815,6 +9019,35 @@ function bindNativeLinks() {
|
|
|
7815
9019
|
} catch {}
|
|
7816
9020
|
}
|
|
7817
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
|
+
|
|
7818
9051
|
function initToken() {
|
|
7819
9052
|
const urlToken = new URLSearchParams(location.search).get('token')
|
|
7820
9053
|
if (urlToken) {
|
|
@@ -7834,6 +9067,7 @@ function initToken() {
|
|
|
7834
9067
|
if (current) current.token = state.token
|
|
7835
9068
|
saveServers()
|
|
7836
9069
|
}
|
|
9070
|
+
if (globalThis.DSH_REMOTE_E2EE_DISABLED === true) disableE2eeState()
|
|
7837
9071
|
$('token-desc').textContent = state.token ? t('token.savedLocal') : t('token.notSet')
|
|
7838
9072
|
$('server-desc').textContent = state.server || t('servers.defaultDesc')
|
|
7839
9073
|
}
|
|
@@ -8102,7 +9336,8 @@ const THEME_META = [
|
|
|
8102
9336
|
{ id: 'nijika', sw: ['#FFF3D5', '#FFFFFF', '#94600C'] },
|
|
8103
9337
|
{ id: 'ryo', sw: ['#E9F1FA', '#FFFFFF', '#315D91'] },
|
|
8104
9338
|
{ id: 'kita', sw: ['#FFE9E5', '#FFFFFF', '#B6373C'] },
|
|
8105
|
-
{ id: 'penguin-logistics', sw: ['#12161B', '#1D252E', '#E9B66F'] }
|
|
9339
|
+
{ id: 'penguin-logistics', sw: ['#12161B', '#1D252E', '#E9B66F'] },
|
|
9340
|
+
{ id: 'miku', sw: ['#F3FFFC', '#FFFFFF', '#126D69'] }
|
|
8106
9341
|
]
|
|
8107
9342
|
|
|
8108
9343
|
function renderThemeBtn() {
|
|
@@ -8135,7 +9370,7 @@ function bindSessionDialogs() {
|
|
|
8135
9370
|
observer.observe($('session-sub'))
|
|
8136
9371
|
}
|
|
8137
9372
|
const actions=$('session-actions'), info=$('session-info');
|
|
8138
|
-
$('btn-session-more').addEventListener('click',()=>actions.showModal());
|
|
9373
|
+
$('btn-session-more').addEventListener('click',()=>{if(typeof refreshSessionAdminActions === 'function')refreshSessionAdminActions();actions.showModal()});
|
|
8139
9374
|
actions.addEventListener('click',e=>{if(e.target===actions)actions.close();else if(e.target.closest('button'))actions.close()},true);
|
|
8140
9375
|
const openInfo=()=>{const s=state.byId.get(state.current);if(!s)return; $('session-info-name').textContent=titleOf(s);$('session-info-path').textContent=s.cwd||t('session.noWorkspace');$('session-info-id').textContent=s.sessionId;$('btn-copy-session-workspace').disabled=!s.cwd;info.showModal()};
|
|
8141
9376
|
$('session-title').addEventListener('click',openInfo);
|
|
@@ -8164,6 +9399,9 @@ function bindUi() {
|
|
|
8164
9399
|
if (state.current) { renderSessionTitle(); renderSessionSub(); renderSessionCards(); renderHistory(true) }
|
|
8165
9400
|
else renderModelMenu()
|
|
8166
9401
|
loadLocalVersion()
|
|
9402
|
+
if (typeof updateBcControlLabels === 'function') updateBcControlLabels()
|
|
9403
|
+
if (typeof updateTurnDiffSettingLabel === 'function') updateTurnDiffSettingLabel()
|
|
9404
|
+
if (state.current && typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
8167
9405
|
if (state.hostInfo) $('host-desc').textContent = hostDescriptionText(state.hostInfo)
|
|
8168
9406
|
$('token-desc').textContent = state.token ? t('token.savedLocal') : t('token.notSet')
|
|
8169
9407
|
})
|
|
@@ -8182,6 +9420,7 @@ function bindUi() {
|
|
|
8182
9420
|
// 底部导航
|
|
8183
9421
|
document.querySelectorAll('.nav-btn').forEach(b =>
|
|
8184
9422
|
b.addEventListener('click', () => showView(b.dataset.view)))
|
|
9423
|
+
$('btn-host-schedule')?.addEventListener('click', () => showView('view-schedule'))
|
|
8185
9424
|
$('overview-primary-action').addEventListener('click', () => {
|
|
8186
9425
|
const button = $('overview-primary-action')
|
|
8187
9426
|
const action = button.dataset.overviewAction
|
|
@@ -8213,6 +9452,12 @@ function bindUi() {
|
|
|
8213
9452
|
archiveSession(archive.dataset.archiveSession)
|
|
8214
9453
|
return
|
|
8215
9454
|
}
|
|
9455
|
+
const unarchive = e.target.closest('[data-unarchive-session]')
|
|
9456
|
+
if (unarchive) {
|
|
9457
|
+
e.stopPropagation()
|
|
9458
|
+
if (typeof unarchiveSessionFromList === 'function') void unarchiveSessionFromList(unarchive.dataset.unarchiveSession)
|
|
9459
|
+
return
|
|
9460
|
+
}
|
|
8216
9461
|
const swipeRow = e.target.closest('[data-session-swipe]')
|
|
8217
9462
|
if (swipeRow?.classList.contains('revealed')) {
|
|
8218
9463
|
swipeRow.classList.remove('revealed')
|
|
@@ -8254,7 +9499,12 @@ function bindUi() {
|
|
|
8254
9499
|
$('btn-insights').addEventListener('click', () => openInsights())
|
|
8255
9500
|
$('context-ring')?.addEventListener('click', () => { if (contextUsage()) void openInsights('context', true) })
|
|
8256
9501
|
$('stats-close').addEventListener('click', () => $('modal-stats').classList.add('hidden'))
|
|
8257
|
-
$('conn-badge').addEventListener('click', () => {
|
|
9502
|
+
$('conn-badge').addEventListener('click', () => {
|
|
9503
|
+
if (window.DshWorkflow?.isMounted()) return window.DshWorkflow.connectionDetails()
|
|
9504
|
+
toast(t('common.refreshing'))
|
|
9505
|
+
openStreams()
|
|
9506
|
+
void refreshAll()
|
|
9507
|
+
})
|
|
8258
9508
|
window.DshExtensions?.bindShortcuts({ trigger: $('btn-plugin-shortcuts'), menu: $('plugin-shortcuts-menu'),
|
|
8259
9509
|
config: () => optionalPluginConfig(), connected: () => !!state.token, hasSession: () => !!state.current,
|
|
8260
9510
|
beforeOpen: () => { closeGroupDrawer({ restoreFocus: false }) },
|
|
@@ -8286,6 +9536,17 @@ function bindUi() {
|
|
|
8286
9536
|
else if (e.key === 'Escape' && isAppVersionWarningOpen()) closeAppVersionWarning(false)
|
|
8287
9537
|
})
|
|
8288
9538
|
$('btn-new-session').addEventListener('click', newSession)
|
|
9539
|
+
const workspaceActions = $('session-workspace-actions')
|
|
9540
|
+
document.addEventListener('click', event => {
|
|
9541
|
+
if (workspaceActions.open && (!workspaceActions.contains(event.target) || event.target.closest('button'))) {
|
|
9542
|
+
workspaceActions.open = false
|
|
9543
|
+
}
|
|
9544
|
+
})
|
|
9545
|
+
workspaceActions.addEventListener('keydown', event => {
|
|
9546
|
+
if (event.key !== 'Escape' || !workspaceActions.open) return
|
|
9547
|
+
workspaceActions.open = false
|
|
9548
|
+
workspaceActions.querySelector('summary').focus()
|
|
9549
|
+
})
|
|
8289
9550
|
$('session-workspace-filter').addEventListener('change', (e) => {
|
|
8290
9551
|
state.workspaceFilter = e.target.value
|
|
8291
9552
|
if (state.workspaceFilter) LS.set('workspaceFilterV1', state.workspaceFilter)
|
|
@@ -8369,10 +9630,14 @@ function bindUi() {
|
|
|
8369
9630
|
$('composer-menu').addEventListener('click', async (e) => {
|
|
8370
9631
|
const chip = e.target.closest('[data-cmd]')
|
|
8371
9632
|
if (chip) {
|
|
8372
|
-
const
|
|
8373
|
-
|
|
8374
|
-
|
|
8375
|
-
|
|
9633
|
+
const command = String(chip.dataset.cmd || '').replace(/^\/+/, '')
|
|
9634
|
+
if (typeof composerTools === 'undefined' || !composerTools?.insertCommand?.(command)) {
|
|
9635
|
+
const input = $('composer-input')
|
|
9636
|
+
if (input.value.trim()) input.value = '/' + command + ' ' + input.value
|
|
9637
|
+
else input.value = '/' + command + ' '
|
|
9638
|
+
input.focus()
|
|
9639
|
+
autosize(input)
|
|
9640
|
+
}
|
|
8376
9641
|
hideComposerMenu()
|
|
8377
9642
|
return
|
|
8378
9643
|
}
|
|
@@ -8409,7 +9674,7 @@ function bindUi() {
|
|
|
8409
9674
|
bindComposerFullscreenGesture()
|
|
8410
9675
|
updateComposerFullscreenButton()
|
|
8411
9676
|
input.addEventListener('keydown', (e) => {
|
|
8412
|
-
if (e.defaultPrevented || e.key !== 'Enter' || e.isComposing) return
|
|
9677
|
+
if (e.defaultPrevented || e.key !== 'Enter' || e.isComposing || composerTools?.keydown(e)) return
|
|
8413
9678
|
if (isMobileDevice() && mobileEnterAction() !== 'send') return
|
|
8414
9679
|
if (!e.shiftKey) { e.preventDefault(); sendMessage() }
|
|
8415
9680
|
})
|
|
@@ -8506,6 +9771,56 @@ function bindUi() {
|
|
|
8506
9771
|
$('group-drawer-trigger').addEventListener('click', () => { groupDrawerOpen() ? closeGroupDrawer() : openGroupDrawer() })
|
|
8507
9772
|
$('group-drawer-close').addEventListener('click', () => closeGroupDrawer())
|
|
8508
9773
|
$('group-drawer-backdrop').addEventListener('click', () => closeGroupDrawer())
|
|
9774
|
+
$('group-drawer-collapse').addEventListener('click', () => setGroupDrawerPanel(''))
|
|
9775
|
+
$('group-drawer-shortcut-options').addEventListener('change', (event) => {
|
|
9776
|
+
const checkbox = event.target.closest('input[data-drawer-shortcut-setting]')
|
|
9777
|
+
if (!checkbox) return
|
|
9778
|
+
const hidden = readGroupDrawerHiddenShortcuts()
|
|
9779
|
+
const key = checkbox.dataset.drawerShortcutSetting
|
|
9780
|
+
if (checkbox.checked) hidden.delete(key)
|
|
9781
|
+
else hidden.add(key)
|
|
9782
|
+
if (!saveGroupDrawerShortcuts(hidden)) checkbox.checked = !checkbox.checked
|
|
9783
|
+
})
|
|
9784
|
+
$('group-drawer-reset-shortcuts').addEventListener('click', () => {
|
|
9785
|
+
if (saveGroupDrawerShortcuts(new Set())) renderGroupDrawerEditor()
|
|
9786
|
+
})
|
|
9787
|
+
$('session-open-drawer').addEventListener('click', () => {
|
|
9788
|
+
$('session-actions').close()
|
|
9789
|
+
$('btn-session-more').focus({ preventScroll: true })
|
|
9790
|
+
openGroupDrawer()
|
|
9791
|
+
})
|
|
9792
|
+
$('group-drawer-host').addEventListener('click', () => {
|
|
9793
|
+
closeGroupDrawer({ restoreFocus: false })
|
|
9794
|
+
showView('view-settings')
|
|
9795
|
+
showSettingsPage('servers')
|
|
9796
|
+
})
|
|
9797
|
+
$('group-drawer').addEventListener('click', (event) => {
|
|
9798
|
+
const target = event.target.closest('[data-drawer-open-panel], [data-drawer-view], [data-drawer-setting], [data-drawer-session]')
|
|
9799
|
+
if (!target) return
|
|
9800
|
+
const { drawerOpenPanel, drawerView, drawerSetting, drawerSession } = target.dataset
|
|
9801
|
+
if (drawerOpenPanel) {
|
|
9802
|
+
setGroupDrawerPanel($('group-drawer').dataset.panel === drawerOpenPanel ? '' : drawerOpenPanel)
|
|
9803
|
+
} else if (drawerSetting && SETTINGS_GROUPS.includes(drawerSetting)) {
|
|
9804
|
+
showView('view-settings')
|
|
9805
|
+
showSettingsPage(drawerSetting)
|
|
9806
|
+
} else if (drawerView) {
|
|
9807
|
+
closeGroupDrawer({ restoreFocus: false })
|
|
9808
|
+
showView(drawerView)
|
|
9809
|
+
} else if (state.byId.has(drawerSession)) {
|
|
9810
|
+
const current = drawerSession === state.current && !$('view-session').classList.contains('hidden')
|
|
9811
|
+
closeGroupDrawer({ restoreFocus: current })
|
|
9812
|
+
if (!current) void openSession(drawerSession)
|
|
9813
|
+
}
|
|
9814
|
+
})
|
|
9815
|
+
$('group-drawer-update')?.addEventListener('click', () => {
|
|
9816
|
+
closeGroupDrawer({ restoreFocus: false })
|
|
9817
|
+
openUpdateSettings()
|
|
9818
|
+
})
|
|
9819
|
+
$('group-drawer-operations-open').addEventListener('click', () => {
|
|
9820
|
+
closeGroupDrawer()
|
|
9821
|
+
if (window.DshWorkflow?.isMounted()) void window.DshWorkflow.showOperations()
|
|
9822
|
+
else showView('view-activity')
|
|
9823
|
+
})
|
|
8509
9824
|
$('group-drawer-list').addEventListener('click', (e) => {
|
|
8510
9825
|
const option = e.target.closest('[data-quick-group]')
|
|
8511
9826
|
if (!option) return
|
|
@@ -8517,6 +9832,12 @@ function bindUi() {
|
|
|
8517
9832
|
closeGroupDrawer({ restoreFocus: false })
|
|
8518
9833
|
showView('view-settings')
|
|
8519
9834
|
showSettingsPage('servers')
|
|
9835
|
+
const addresses = $('workflow-settings-servers-local')
|
|
9836
|
+
if (addresses) {
|
|
9837
|
+
addresses.open = true
|
|
9838
|
+
addresses.querySelector('summary')?.focus({ preventScroll: true })
|
|
9839
|
+
addresses.scrollIntoView({ block: 'start' })
|
|
9840
|
+
}
|
|
8520
9841
|
})
|
|
8521
9842
|
document.addEventListener('keydown', keepGroupDrawerFocus)
|
|
8522
9843
|
document.addEventListener('click', (e) => {
|
|
@@ -8673,6 +9994,7 @@ window.addEventListener('dsh-native-insets', applyNativeInsets)
|
|
|
8673
9994
|
async function boot() {
|
|
8674
9995
|
initToken()
|
|
8675
9996
|
bindUi()
|
|
9997
|
+
if (typeof initBcFeatures === 'function') initBcFeatures()
|
|
8676
9998
|
syncBgConfig()
|
|
8677
9999
|
renderAnnouncementBoard()
|
|
8678
10000
|
renderLangBtn()
|
|
@@ -8681,7 +10003,11 @@ async function boot() {
|
|
|
8681
10003
|
applyNativeInsets()
|
|
8682
10004
|
showView('view-activity')
|
|
8683
10005
|
updateConn()
|
|
8684
|
-
|
|
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()
|
|
8685
10011
|
if (!state.token) {
|
|
8686
10012
|
showView('view-activity')
|
|
8687
10013
|
overviewStarting=false
|
|
@@ -8689,9 +10015,11 @@ async function boot() {
|
|
|
8689
10015
|
} else {
|
|
8690
10016
|
// 多服务器: 启动时静默测速一次, 选最快的连接(同源页面也参与比较)
|
|
8691
10017
|
if (!doctorSessionHandoff) await selectFastestServer({ silent: true, reconnect: false })
|
|
8692
|
-
await maybeWarnAppBehindGateway({ probe: true })
|
|
8693
10018
|
overviewStarting=false
|
|
8694
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(() => {})
|
|
8695
10023
|
await Promise.all([refreshAll(),refreshHostDescription()])
|
|
8696
10024
|
loadDshControl()
|
|
8697
10025
|
}
|
|
@@ -8700,8 +10028,10 @@ async function boot() {
|
|
|
8700
10028
|
startAnnouncementPolling()
|
|
8701
10029
|
scheduleStartupNotices()
|
|
8702
10030
|
renderPending()
|
|
10031
|
+
initTurnDiffSetting()
|
|
8703
10032
|
pendingNavigationReady = true
|
|
8704
10033
|
void openPendingNavigation()
|
|
10034
|
+
window.dispatchEvent(new Event('dsh-relay-activation'))
|
|
8705
10035
|
}
|
|
8706
10036
|
|
|
8707
10037
|
document.addEventListener('DOMContentLoaded', boot)
|
|
@@ -8712,10 +10042,12 @@ function mountWorkflow() {
|
|
|
8712
10042
|
desktop: false,
|
|
8713
10043
|
start: () => { if (!$('view-activity').classList.contains('hidden')) showView('view-home') },
|
|
8714
10044
|
snapshot: () => ({ token: !!state.token, host: currentServerEntry()?.note || state.server || location.host,
|
|
10045
|
+
connectionIssue: activeConnectionIssue(), address: state.server || location.host, offline: navigator.onLine === false,
|
|
8715
10046
|
gateway: activeGatewayHealth()?.ok || !!state.streamsOk?.mux, dsh: dshReachable(),
|
|
8716
10047
|
mux: !!state.streamsOk?.mux, hostEvents: !!state.streamsOk?.host,
|
|
8717
10048
|
pending: state.approvals.length + state.questions.length, busy: composerIsBusy(), sending: composerSending }),
|
|
8718
10049
|
settings: name => { showView('view-settings'); showSettingsPage(name) },
|
|
10050
|
+
cloudRelayReady: () => pendingNavigationReady,
|
|
8719
10051
|
plugins: () => showView('view-plugins'), models: loadSessionModels, send: sendMessage,
|
|
8720
10052
|
feedback: openFeedbackModal,
|
|
8721
10053
|
doctor: openDoctor,
|
|
@@ -8730,18 +10062,19 @@ function mountWorkflow() {
|
|
|
8730
10062
|
state.workspaceFilter=value.workspace.workspaceId;closeWorkspaceModal();await newSession()
|
|
8731
10063
|
}catch(error){if(connection.valid())toast(error.message,'err')}
|
|
8732
10064
|
},
|
|
8733
|
-
command: runSlashCommand, refresh: refreshAll, retry: () => { startOverviewDetection(true); void refreshAll() },
|
|
10065
|
+
command: runSlashCommand, refresh: refreshAll, retry: () => { openStreams(); startOverviewDetection(true); void refreshAll() },
|
|
8734
10066
|
operations: () => { const connection=captureConnection(); return { url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid } },
|
|
8735
|
-
relay: () => { const connection=captureConnection(); return { url:()=>adminApiUrl('/admin/api/relay'),headers:{authorization:'Bearer '+connection.token},valid:connection.valid,connected:!!connection.token,setupId:relaySetupFor(connection) } },
|
|
8736
|
-
|
|
8737
|
-
|
|
8738
|
-
|
|
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) } },
|
|
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) => {
|
|
8739
10072
|
if (!connection.valid()) return
|
|
8740
10073
|
const token = connection.headers.authorization.slice(7)
|
|
8741
10074
|
closeStream('mux'); closeStream('host'); stopPolling(); state.wsTicket = null
|
|
8742
10075
|
if (applyPairUrl('dshremote://pair?' + new URLSearchParams({ server: origin, token }).toString())) { void refreshAll(); openStreams() }
|
|
8743
10076
|
},
|
|
8744
|
-
e2eeModeChange: (origin, connection) => {
|
|
10077
|
+
e2eeModeChange: globalThis.DSH_REMOTE_E2EE_DISABLED === true ? undefined : (origin, connection) => {
|
|
8745
10078
|
if (!connection.valid() || new URL(apiUrl('/relay'),location.href).origin !== origin) return
|
|
8746
10079
|
closeStream('mux'); closeStream('host'); stopPolling(); state.wsTicket = null
|
|
8747
10080
|
syncBgConfig(); void refreshAll(); openStreams()
|
|
@@ -8774,7 +10107,7 @@ function mountWorkflow() {
|
|
|
8774
10107
|
|
|
8775
10108
|
function mountOnboarding() {
|
|
8776
10109
|
window.DshOnboarding?.mount({
|
|
8777
|
-
snapshot: () => ({ connection: connectionGeneration, session: state.current,
|
|
10110
|
+
snapshot: () => ({ connection: connectionGeneration, session: state.current, hasSessions: state.sessions.length > 0,
|
|
8778
10111
|
connected: navigator.onLine !== false && !!state.token && dshReachable()
|
|
8779
10112
|
&& (!!state.streamsOk?.mux || (state.streamMode === 'poll' && !!state.hostInfo)),
|
|
8780
10113
|
sessionReady: state.sessionRecovery.status === 'ready' && !state.history.loading }),
|
|
@@ -8815,6 +10148,7 @@ async function clearWorkflowData(kind) {
|
|
|
8815
10148
|
if(kind!=='images')cancelHistoryLoad()
|
|
8816
10149
|
const results=[]
|
|
8817
10150
|
if(kind!=='images')results.push(await window.DshHistory.cacheClear())
|
|
10151
|
+
if(kind!=='images')results.push(clearAllSessionCaches())
|
|
8818
10152
|
if(kind!=='history')results.push(await window.DshImageCache.clear())
|
|
8819
10153
|
if(results.includes(false))return toast(english?'Some caches could not be cleared. Retry shortly.':'部分缓存未能清除,请稍后重试。','err')
|
|
8820
10154
|
return toast(english ? 'Cache cleared' : '缓存已清除', 'ok')
|
|
@@ -8823,14 +10157,17 @@ async function clearWorkflowData(kind) {
|
|
|
8823
10157
|
window.NativeBackground?.savePeakReminderConfig?.(JSON.stringify({ enabled:false }))
|
|
8824
10158
|
window.NativeBackground?.setPendingNotificationsEnabled?.(false)
|
|
8825
10159
|
if (kind === 'connection') {
|
|
8826
|
-
const connection=captureConnection(),
|
|
10160
|
+
const connection = captureConnection(), scopes = connectionCacheReadKeys('history')
|
|
8827
10161
|
cancelHistoryLoad()
|
|
8828
|
-
await
|
|
8829
|
-
|
|
10162
|
+
await Promise.all(scopes.flatMap(scope => [
|
|
10163
|
+
window.DshImageCache.clear(scope),
|
|
10164
|
+
window.DshHistory.cacheClear(scope),
|
|
10165
|
+
clearSessionCache(scope),
|
|
10166
|
+
]))
|
|
8830
10167
|
if(!connection.valid())return
|
|
8831
10168
|
const current = currentServerEntry()
|
|
8832
10169
|
const remaining = current ? state.servers.filter(server => server.id !== current.id) : state.servers
|
|
8833
|
-
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')
|
|
8834
10171
|
if (current) state.servers = state.servers.filter(server => server.id !== current.id)
|
|
8835
10172
|
state.groupActive[state.activeGroup] = ''
|
|
8836
10173
|
state.token = ''; state.server = ''; LS.del('token'); LS.del('server'); saveServers()
|
|
@@ -8842,9 +10179,10 @@ async function clearWorkflowData(kind) {
|
|
|
8842
10179
|
clearTimeout(scheduleHistoryCacheSave._t)
|
|
8843
10180
|
await window.DshHistory.cacheClear()
|
|
8844
10181
|
await window.DshImageCache.clear()
|
|
10182
|
+
clearAllSessionCaches()
|
|
8845
10183
|
resetAnnouncementStorage()
|
|
8846
10184
|
window.DshWorkflow.clearStorage()
|
|
8847
|
-
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')
|
|
8848
10186
|
location.reload()
|
|
8849
10187
|
}
|
|
8850
10188
|
|
|
@@ -8894,7 +10232,7 @@ globalThis.DshApprovalSummary?.mount({ capture: captureConnection, items: () =>
|
|
|
8894
10232
|
url: (connection, path) => connection.server + path,
|
|
8895
10233
|
headers: connection => ({ authorization: 'Bearer ' + connection.token, ...clientIdHeaders() }) })
|
|
8896
10234
|
globalThis.DshCacheUpgrade?.mount({
|
|
8897
|
-
scopes:()=>state.servers.
|
|
10235
|
+
scopes:()=>state.servers.flatMap(server=>connectionCacheReadKeys('history',server.url,serverToken(server))),
|
|
8898
10236
|
safe:()=>!state.current&&!state.approvals.length&&!state.questions.length&&!composerSending
|
|
8899
10237
|
&&![...document.querySelectorAll('textarea,input:not([type="checkbox"]):not([type="radio"])')].some(input=>input.getBoundingClientRect().width&&input.value)
|
|
8900
10238
|
&&!document.querySelector('[data-transfer-id]')&&!state.sessions.some(session=>session.running)
|