dsh-remote-plugin 0.8.7 → 0.9.0
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 +659 -130
- package/index.mjs +33 -1
- package/package.json +8 -3
- package/public/activity.js +196 -52
- package/public/admin.html +34 -32
- package/public/admin.js +11 -2
- package/public/app.js +1341 -223
- 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 +104 -76
- package/public/desktop/desktop.js +668 -101
- package/public/diagnostics.js +30 -4
- package/public/e2ee-transport.js +154 -7
- package/public/file-inbox.js +77 -18
- package/public/genui.css +10 -0
- package/public/genui.js +22 -4
- package/public/history.js +15 -2
- 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 +347 -140
- package/public/md.js +21 -1
- package/public/network.js +33 -1
- package/public/onboarding.js +3 -3
- package/public/operations.js +26 -12
- package/public/plan-review.css +297 -0
- package/public/plan-review.js +621 -0
- package/public/plugin.html +29 -27
- package/public/relay-autopair.js +25 -10
- package/public/relay-settings.css +11 -0
- package/public/relay-settings.js +350 -28
- 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/penguin-logistics/cargo.svg +4 -0
- package/public/skins/penguin-logistics/console.svg +4 -0
- package/public/skins/penguin-logistics/mark.svg +4 -0
- package/public/skins/penguin-logistics/radio.svg +4 -0
- package/public/skins/penguin-logistics/skin.css +292 -0
- package/public/skins/penguin-logistics/standing.png +0 -0
- package/public/skins/ryo/preview.html +6 -6
- package/public/slash-suggestions.css +43 -0
- package/public/slash-suggestions.js +196 -0
- package/public/sponsor-entry.js +11 -3
- package/public/styles.css +141 -21
- package/public/subagents.css +7 -0
- package/public/subagents.js +83 -10
- package/public/theme-vars.css +102 -3
- package/public/theme.js +7 -4
- 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 +322 -43
- package/public/workflow.js +148 -44
package/public/app.js
CHANGED
|
@@ -77,7 +77,6 @@ const state = {
|
|
|
77
77
|
approvalRecordsServer: null,
|
|
78
78
|
questions: [], // 待处理提问
|
|
79
79
|
queues: {}, // sessionId -> queue items
|
|
80
|
-
queueSteering: {}, // sessionId:itemId -> pending steer request
|
|
81
80
|
compactionBootAt: Date.now(),
|
|
82
81
|
compactions: {}, // sessionId -> {active, phase, startedAt, message, source}
|
|
83
82
|
pendingCommands: {}, // sessionId -> command name; waits briefly before showing generic progress
|
|
@@ -104,6 +103,7 @@ const state = {
|
|
|
104
103
|
wb: null,
|
|
105
104
|
wbProjects: [],
|
|
106
105
|
wbArchived: [],
|
|
106
|
+
wbPinned: [],
|
|
107
107
|
wbOpen: false,
|
|
108
108
|
wbOpenProjects: {},
|
|
109
109
|
subagentSessions: {}
|
|
@@ -120,20 +120,32 @@ for (const key of ['server', 'token']) {
|
|
|
120
120
|
if (next === value) return
|
|
121
121
|
cancelHistoryLoad()
|
|
122
122
|
value = next; connectionGeneration++
|
|
123
|
+
window.DshSlashSuggestions?.close()
|
|
123
124
|
window.DshImagePreview?.reset?.()
|
|
124
125
|
clearTimeout(state.refreshTimer); state.refreshTimer = null
|
|
125
126
|
state.sessions = []; state.byId.clear(); state.pendingProjections.clear(); state.runtimeErrors = new Map()
|
|
126
127
|
state.hostInfo = null
|
|
127
|
-
if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){
|
|
128
|
+
if (typeof closeStream === 'function' && typeof streamMeta !== 'undefined') {
|
|
129
|
+
stopPolling()
|
|
130
|
+
clearReconnect()
|
|
131
|
+
for (const kind of ['mux', 'host']) {
|
|
132
|
+
closeStream(kind)
|
|
133
|
+
streamMeta[kind].attempt = 0
|
|
134
|
+
streamMeta[kind].failures = 0
|
|
135
|
+
}
|
|
136
|
+
state.streamMode = 'ws'
|
|
137
|
+
state.pollSeq = { mux: 0, host: 0 }
|
|
138
|
+
state.errCount = 0
|
|
139
|
+
}
|
|
128
140
|
state.current = null; state.history = emptyHistory(); state.subagentSessions = {}; window.DshSubagents?.reset()
|
|
129
141
|
state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
|
|
130
142
|
state.modelSettings = { status: 'idle', error: '', writable: false, hasDocument: false, providers: [], namespaces: [], credentials: {} }; state.modelEditor = null
|
|
131
143
|
state.goalEdit = null; state.goalEditContext = null
|
|
132
144
|
state.approvals = []; state.questions = []; state.questionModal = null
|
|
133
|
-
state.queues = {}; state.jobs = {}; state.
|
|
145
|
+
state.queues = {}; state.jobs = {}; state.compactions = {}; state.compactionTerminals = {}; state.compactionSeqs = {}; state.compactionBootAt = Date.now(); state.pendingCommands = {}; state.sessionTurnTimes = {}
|
|
134
146
|
state.sessionActivity = new Set(); state.pendingPrompts = new Set()
|
|
135
147
|
state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
|
|
136
|
-
state.wb = null; state.wbProjects = []; state.wbArchived = []; state.workspaceFilter = ''; state.fs.workspaceId = ''; clearTimeout(scheduleHistoryCacheSave._t)
|
|
148
|
+
state.wb = null; state.wbProjects = []; state.wbArchived = []; state.wbPinned = []; state.workspaceFilter = ''; state.fs.workspaceId = ''; clearTimeout(scheduleHistoryCacheSave._t)
|
|
137
149
|
window.DshPluginCenter?.close()
|
|
138
150
|
window.DshInsights?.close()
|
|
139
151
|
window.DshExtensions?.close()
|
|
@@ -144,7 +156,11 @@ for (const key of ['server', 'token']) {
|
|
|
144
156
|
if (typeof document !== 'undefined') document.getElementById('btn-insights')?.classList.add('hidden')
|
|
145
157
|
if(typeof document!=='undefined') {
|
|
146
158
|
const identityGeneration=connectionGeneration
|
|
147
|
-
queueMicrotask(()=>{
|
|
159
|
+
queueMicrotask(() => {
|
|
160
|
+
if (identityGeneration !== connectionGeneration) return
|
|
161
|
+
if (typeof groupDrawerOpen === 'function' && groupDrawerOpen() && $('group-drawer').dataset.panel) closeGroupDrawer()
|
|
162
|
+
if (typeof startOverviewDetection === 'function') startOverviewDetection(true, true)
|
|
163
|
+
})
|
|
148
164
|
document.getElementById('history')?.replaceChildren?.()
|
|
149
165
|
const generation=connectionGeneration
|
|
150
166
|
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()})
|
|
@@ -185,6 +201,7 @@ function toast(text, kind = '') {
|
|
|
185
201
|
/* ---------------- 应用内选择抽屉 ---------------- */
|
|
186
202
|
const CUSTOM_SELECT_TITLES = {
|
|
187
203
|
'session-workspace-filter': 'workspace.select',
|
|
204
|
+
'session-search-workspace': 'workspace.select',
|
|
188
205
|
'session-sort': 'sessions.sortLabel',
|
|
189
206
|
'fs-workspace': 'workspace.select',
|
|
190
207
|
'mobile-enter-action': 'settings.mobileEnterTitle',
|
|
@@ -309,7 +326,10 @@ function initCustomSelects() {
|
|
|
309
326
|
$('custom-select-close').addEventListener('click', () => closeCustomSelect())
|
|
310
327
|
$('custom-select-cancel').addEventListener('click', () => closeCustomSelect())
|
|
311
328
|
document.addEventListener('keydown', (event) => {
|
|
312
|
-
if (event.key === 'Escape' && customSelectCurrent)
|
|
329
|
+
if (event.key === 'Escape' && customSelectCurrent) {
|
|
330
|
+
event.preventDefault()
|
|
331
|
+
closeCustomSelect()
|
|
332
|
+
}
|
|
313
333
|
})
|
|
314
334
|
}
|
|
315
335
|
|
|
@@ -362,7 +382,7 @@ function openDoctor() {
|
|
|
362
382
|
})
|
|
363
383
|
}
|
|
364
384
|
function openFeedbackModal(options = {}) {
|
|
365
|
-
if (!options.preserveDraft) {
|
|
385
|
+
if (!options.preserveDraft && !state.feedbackConnectionRejected) {
|
|
366
386
|
state.feedbackType = 'bug'
|
|
367
387
|
document.querySelectorAll('#fb-chips .fb-chip').forEach(b => b.classList.toggle('current', b.dataset.fbType === 'bug'))
|
|
368
388
|
$('fb-msg').value = ''
|
|
@@ -427,6 +447,7 @@ async function submitFeedback() {
|
|
|
427
447
|
let json = {}
|
|
428
448
|
try { json = await res.json() } catch {}
|
|
429
449
|
if (res.ok && json.ok) { closeFeedbackModal(); openFeedbackSuccess()
|
|
450
|
+
state.feedbackConnectionRejected = false
|
|
430
451
|
const status=$('feedback-diagnostics-status'),saved=json.diagnostics?.saved===true&&json.diagnostics.reportId===clientDiagnostics?.reportId
|
|
431
452
|
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.':'反馈已收到,但服务器未确认完整诊断日志已保存。请复制或导出本地日志补充。')):''
|
|
432
453
|
status.classList.toggle('hidden',!clientDiagnostics)
|
|
@@ -437,6 +458,10 @@ async function submitFeedback() {
|
|
|
437
458
|
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') }
|
|
438
459
|
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') }
|
|
439
460
|
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') }
|
|
461
|
+
else if (res.status === 401 || res.status === 426) {
|
|
462
|
+
state.feedbackConnectionRejected = true
|
|
463
|
+
toast(t('conn.feedbackBlocked'), 'err')
|
|
464
|
+
}
|
|
440
465
|
else { toast(t('feedback.submitFailed', { msg: json.error || res.status }), 'err') }
|
|
441
466
|
} catch(error) {
|
|
442
467
|
diagnostic?.fail(error)
|
|
@@ -504,14 +529,29 @@ function relaySetupFor(connection) {
|
|
|
504
529
|
if (relaySetup && relaySetup.token === connection.token && relaySetup.servers.includes(connection.server)) return relaySetup.id
|
|
505
530
|
return ''
|
|
506
531
|
}
|
|
507
|
-
function offerLocalRelayPairing(connection=captureConnection(), force=false) {
|
|
532
|
+
function offerLocalRelayPairing(connection=captureConnection(), force=false, activationId='') {
|
|
508
533
|
if (!connection.token || !connection.valid()) return
|
|
509
534
|
return window.DshRelayAutoPair?.offer({
|
|
510
535
|
connection:()=>({valid:connection.valid,url:path=>connection.server+path,headers:{authorization:'Bearer '+connection.token},setupId:relaySetupFor(connection)}),
|
|
511
|
-
onPaired:saveAutoPairedRelay,force,
|
|
536
|
+
onPaired:saveAutoPairedRelay,force,activationId,
|
|
512
537
|
onStatus:(message,error)=>{if(force&&error&&connection.valid())toast(message,'err')},
|
|
513
538
|
})
|
|
514
539
|
}
|
|
540
|
+
let relayActivationSync = null
|
|
541
|
+
function syncRelayActivation(activationId, force = false) {
|
|
542
|
+
if (!CAP?.isNativePlatform?.() || !/^[a-f0-9]{32}$/.test(activationId || '')) return
|
|
543
|
+
if (relayActivationSync?.id === activationId && relayActivationSync.connection.valid()) return relayActivationSync.task
|
|
544
|
+
const connection = captureConnection()
|
|
545
|
+
const job = { id: activationId, connection }
|
|
546
|
+
job.task = Promise.resolve(offerLocalRelayPairing(connection, force, activationId))
|
|
547
|
+
.catch(() => ({ ok: false }))
|
|
548
|
+
.then(result => {
|
|
549
|
+
if (!result?.ok && relayActivationSync === job) relayActivationSync = null
|
|
550
|
+
return result
|
|
551
|
+
})
|
|
552
|
+
relayActivationSync = job
|
|
553
|
+
return job.task
|
|
554
|
+
}
|
|
515
555
|
function apiUrl(path) {
|
|
516
556
|
return (state.server || '') + path
|
|
517
557
|
}
|
|
@@ -591,13 +631,13 @@ async function rpc(method, payload = {}, timeoutMs = 45000, cancellation = null)
|
|
|
591
631
|
else if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
|
|
592
632
|
opts.signal = AbortSignal.timeout(timeoutMs)
|
|
593
633
|
}
|
|
594
|
-
const operation = window.DshOperations?.supports(method) && activeGatewayCapability('operations') === true
|
|
634
|
+
const operation = window.DshOperations?.supports(method) && (window.DshOperations.requiresReceipt?.(method) || activeGatewayCapability('operations') === true)
|
|
595
635
|
const connection = operation ? captureConnection() : null
|
|
596
636
|
const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
|
|
597
637
|
const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
|
|
598
638
|
diagnostic?.end({phase:'response',httpStatus:res.status})
|
|
599
639
|
if (res.status === 401) throw new Error('AUTH')
|
|
600
|
-
if (!res.ok)
|
|
640
|
+
if (!res.ok) { const error = new Error('HTTP ' + res.status); error.status = res.status; throw error }
|
|
601
641
|
const full = await res.json()
|
|
602
642
|
if (!full?.result) throw new Error(t('err.badResponse'))
|
|
603
643
|
if (!full.result.ok) {
|
|
@@ -641,11 +681,20 @@ function notifyPendingOperation(error, connection) {
|
|
|
641
681
|
}
|
|
642
682
|
async function safeRpc(method, payload, errText) {
|
|
643
683
|
const connection = captureConnection()
|
|
644
|
-
try {
|
|
684
|
+
try {
|
|
685
|
+
const value = await rpc(method, payload)
|
|
686
|
+
if (!connection.valid()) return null
|
|
687
|
+
if (method === 'session.list' && activeConnectionIssue()) {
|
|
688
|
+
connectionIssue = null
|
|
689
|
+
updateConn()
|
|
690
|
+
}
|
|
691
|
+
return value
|
|
692
|
+
}
|
|
645
693
|
catch (e) {
|
|
646
694
|
if (e.operationPending) { notifyPendingOperation(e, connection); return null }
|
|
647
695
|
if (!connection.valid()) return null
|
|
648
696
|
if (e.message === 'AUTH') authFailure()
|
|
697
|
+
else if (e.status === 426) authFailure(426)
|
|
649
698
|
else toast(errText ? `${errText}:${e.message}` : e.message, 'err')
|
|
650
699
|
return null
|
|
651
700
|
}
|
|
@@ -713,10 +762,18 @@ async function refreshHostDescription({ notify = false } = {}) {
|
|
|
713
762
|
return job
|
|
714
763
|
}
|
|
715
764
|
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
765
|
+
let connectionIssue = null
|
|
766
|
+
|
|
767
|
+
function activeConnectionIssue() {
|
|
768
|
+
return connectionIssue?.connection.valid() ? connectionIssue.status : null
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
function authFailure(status = 401) {
|
|
772
|
+
const previous = activeConnectionIssue()
|
|
773
|
+
if (previous === status) return
|
|
774
|
+
connectionIssue = { connection: captureConnection(), status }
|
|
775
|
+
updateConn()
|
|
776
|
+
if (!previous) toast(t(status === 426 ? 'conn.pairingNotice' : 'conn.authNotice'), 'err')
|
|
720
777
|
}
|
|
721
778
|
|
|
722
779
|
/* ---------------- 多服务器分组管理 + 自动选优 ---------------- */
|
|
@@ -839,26 +896,15 @@ function serverCandidates() {
|
|
|
839
896
|
return list
|
|
840
897
|
}
|
|
841
898
|
|
|
842
|
-
|
|
899
|
+
function pingServer(base, token) {
|
|
843
900
|
const u = String(base || '').replace(/\/+$/, '')
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
const timer = setTimeout(() => ctrl.abort(), 3500)
|
|
848
|
-
try {
|
|
849
|
-
const res = await fetch(u + '/health?probe=live&t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
|
|
850
|
-
if (!res.ok) return Infinity
|
|
851
|
-
const health = await res.json().catch(() => null)
|
|
852
|
-
if (health && typeof health === 'object') {
|
|
901
|
+
return DshNetwork.probeGateway(u, {
|
|
902
|
+
headers: token === undefined ? undefined : { authorization: token ? 'Bearer ' + token : '', 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
|
|
903
|
+
onHealth: health => {
|
|
853
904
|
state.gatewayHealth[u] = health
|
|
854
905
|
renderOverview()
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
} catch {
|
|
858
|
-
return Infinity
|
|
859
|
-
} finally {
|
|
860
|
-
clearTimeout(timer)
|
|
861
|
-
}
|
|
906
|
+
},
|
|
907
|
+
})
|
|
862
908
|
}
|
|
863
909
|
|
|
864
910
|
function activeGatewayCapability(name) {
|
|
@@ -879,6 +925,37 @@ function dshReachable() {
|
|
|
879
925
|
return !!state.hostInfo && state.hostInfo.metadataOnly !== true
|
|
880
926
|
}
|
|
881
927
|
|
|
928
|
+
let connectionHealthProbe = null
|
|
929
|
+
function currentConnectionHealth() {
|
|
930
|
+
return connectionHealthProbe?.connection.valid() ? connectionHealthProbe.health : undefined
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
async function refreshConnectionHealth() {
|
|
934
|
+
if (!state.token || navigator.onLine === false) return null
|
|
935
|
+
const current = connectionHealthProbe?.connection.valid() ? connectionHealthProbe : null
|
|
936
|
+
if (current?.task) return current.task
|
|
937
|
+
const connection = captureConnection()
|
|
938
|
+
const base = String(connection.server || location.origin).replace(/\/+$/, '')
|
|
939
|
+
const probe = { connection, health: current?.health, task: null }
|
|
940
|
+
connectionHealthProbe = probe
|
|
941
|
+
probe.task = (async () => {
|
|
942
|
+
let health = null
|
|
943
|
+
try {
|
|
944
|
+
const response = await fetch(base + '/health?probe=fresh', { cache: 'no-store', signal: AbortSignal.timeout(6500) })
|
|
945
|
+
const value = response.ok ? await response.json() : null
|
|
946
|
+
if (value?.ok === true) health = value
|
|
947
|
+
} catch {}
|
|
948
|
+
if (probe !== connectionHealthProbe || !connection.valid()) return null
|
|
949
|
+
probe.health = health
|
|
950
|
+
if (health) state.gatewayHealth[base] = health
|
|
951
|
+
else delete state.gatewayHealth[base]
|
|
952
|
+
probe.task = null
|
|
953
|
+
updateConn()
|
|
954
|
+
return health
|
|
955
|
+
})()
|
|
956
|
+
return probe.task
|
|
957
|
+
}
|
|
958
|
+
|
|
882
959
|
async function selectFastestServer({ silent = false, reconnect = true } = {}) {
|
|
883
960
|
const request = selectFastestServer.request = (selectFastestServer.request || 0) + 1
|
|
884
961
|
const connection = captureConnection(), group = state.activeGroup
|
|
@@ -894,7 +971,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
|
|
|
894
971
|
let ms = Infinity
|
|
895
972
|
|
|
896
973
|
if (state.autoSelect[state.activeGroup] !== false) {
|
|
897
|
-
const measured = await Promise.all(candidates.map(async
|
|
974
|
+
const measured = await Promise.all(candidates.map(async server => [server, await pingServer(server.url, server.token)]))
|
|
898
975
|
if (!valid()) return null
|
|
899
976
|
for (const [server, latency] of measured) state.serverLatency[serverKey(server)] = latency
|
|
900
977
|
best = candidates
|
|
@@ -983,20 +1060,51 @@ function closeGroupMenu() {
|
|
|
983
1060
|
}
|
|
984
1061
|
|
|
985
1062
|
let groupDrawerReturnFocus = null
|
|
1063
|
+
let groupDrawerRoute = null
|
|
986
1064
|
|
|
987
1065
|
function groupDrawerOpen() {
|
|
988
|
-
return
|
|
1066
|
+
return $('group-drawer')?.classList.contains('hidden') === false
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
async function updateGroupDrawerRoute() {
|
|
1070
|
+
const status = $('group-drawer-connection')
|
|
1071
|
+
if (!status || !groupDrawerOpen()) return
|
|
1072
|
+
if (groupDrawerRoute?.connection.valid()) {
|
|
1073
|
+
status.textContent = t('groups.drawerRoute.' + groupDrawerRoute.category)
|
|
1074
|
+
return
|
|
1075
|
+
}
|
|
1076
|
+
const connection = captureConnection()
|
|
1077
|
+
const base = updateBase()
|
|
1078
|
+
const route = { connection, category: connection.token && base ? 'checking' : 'disconnected' }
|
|
1079
|
+
groupDrawerRoute = route
|
|
1080
|
+
status.textContent = t('groups.drawerRoute.' + route.category)
|
|
1081
|
+
if (route.category === 'disconnected') return
|
|
1082
|
+
|
|
1083
|
+
try {
|
|
1084
|
+
const response = await fetch(adminApiUrl('/admin/api/relay'), {
|
|
1085
|
+
headers: { authorization: 'Bearer ' + connection.token },
|
|
1086
|
+
cache: 'no-store',
|
|
1087
|
+
redirect: 'error',
|
|
1088
|
+
signal: AbortSignal.timeout(5000),
|
|
1089
|
+
})
|
|
1090
|
+
const data = response.ok ? await response.json() : null
|
|
1091
|
+
route.category = window.DshRelaySettings?.connectionCategory?.(data, base) || 'unknown'
|
|
1092
|
+
} catch {
|
|
1093
|
+
route.category = 'unknown'
|
|
1094
|
+
}
|
|
1095
|
+
if (groupDrawerRoute === route && connection.valid()) {
|
|
1096
|
+
status.textContent = t('groups.drawerRoute.' + route.category)
|
|
1097
|
+
}
|
|
989
1098
|
}
|
|
990
1099
|
|
|
991
1100
|
function renderGroupDrawer() {
|
|
992
1101
|
const trigger = $('group-drawer-trigger')
|
|
993
1102
|
const brandGroup = $('brand-group-name')
|
|
994
|
-
const current = $('group-drawer-current')
|
|
995
1103
|
const list = $('group-drawer-list')
|
|
996
1104
|
if (brandGroup) brandGroup.textContent = state.activeGroup
|
|
997
|
-
if (trigger) trigger.setAttribute('aria-label', t('groups.
|
|
998
|
-
if (
|
|
999
|
-
|
|
1105
|
+
if (trigger) trigger.setAttribute('aria-label', t('groups.drawerOpenFor', { group: state.activeGroup }))
|
|
1106
|
+
if (!list || $('group-drawer-groups-panel').hidden || !groupDrawerOpen()) return
|
|
1107
|
+
void updateGroupDrawerRoute()
|
|
1000
1108
|
list.innerHTML = state.groups.map(group => {
|
|
1001
1109
|
const servers = groupServers(group)
|
|
1002
1110
|
const selected = group === state.activeGroup
|
|
@@ -1008,18 +1116,253 @@ function renderGroupDrawer() {
|
|
|
1008
1116
|
}).join('')
|
|
1009
1117
|
}
|
|
1010
1118
|
|
|
1119
|
+
function renderGroupDrawerSessions() {
|
|
1120
|
+
const list = $('group-drawer-sessions')
|
|
1121
|
+
if (!list || $('group-drawer-recent').hidden || !groupDrawerOpen()) return
|
|
1122
|
+
const archived = new Set(state.wbArchived || [])
|
|
1123
|
+
const sessions = state.sessions.filter(session => isVisibleSession(session) && !archived.has(session.sessionId))
|
|
1124
|
+
.sort((a, b) => sessionSortTime(b) - sessionSortTime(a)).slice(0, 5)
|
|
1125
|
+
$('group-drawer-recent-empty').hidden = sessions.length > 0
|
|
1126
|
+
const rows = sessions.map(session => {
|
|
1127
|
+
const id = session.sessionId
|
|
1128
|
+
const title = esc(sessionLabelOf(session))
|
|
1129
|
+
const current = id === state.current && !$('view-session').classList.contains('hidden')
|
|
1130
|
+
return `<button type="button" class="group-drawer-session${current ? ' current' : ''}" data-drawer-session="${esc(id)}"${current ? ' aria-current="true"' : ''}>
|
|
1131
|
+
<span class="group-drawer-session-title" title="${title}">${title}</span>
|
|
1132
|
+
<span class="group-drawer-session-meta">${esc(sessionWorkspaceName(session))}</span>
|
|
1133
|
+
</button>`
|
|
1134
|
+
}).join('')
|
|
1135
|
+
if (list.innerHTML === rows) return
|
|
1136
|
+
const focusedId = list.contains(document.activeElement) ? document.activeElement.dataset.drawerSession : null
|
|
1137
|
+
list.innerHTML = rows
|
|
1138
|
+
if (focusedId) {
|
|
1139
|
+
const focus = [...list.children].find(row => row.dataset.drawerSession === focusedId) || $('group-drawer-panel-title')
|
|
1140
|
+
focus.focus({ preventScroll: true })
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
const GROUP_DRAWER_SHORTCUT_PREFS = 'groupDrawerHiddenShortcutsV1'
|
|
1145
|
+
|
|
1146
|
+
function readGroupDrawerHiddenShortcuts() {
|
|
1147
|
+
const stored = cacheRead(GROUP_DRAWER_SHORTCUT_PREFS)
|
|
1148
|
+
return new Set(Array.isArray(stored) ? stored.filter(key => typeof key === 'string') : [])
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
function applyGroupDrawerShortcuts(hidden) {
|
|
1152
|
+
for (const shortcut of $('group-drawer').querySelectorAll('[data-drawer-shortcut]')) {
|
|
1153
|
+
shortcut.hidden = hidden.has(shortcut.dataset.drawerShortcut)
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
function saveGroupDrawerShortcuts(hidden) {
|
|
1158
|
+
if (!LS.set(GROUP_DRAWER_SHORTCUT_PREFS, JSON.stringify([...hidden]))) {
|
|
1159
|
+
toast(t('groups.drawerSaveFailed'), 'err')
|
|
1160
|
+
return false
|
|
1161
|
+
}
|
|
1162
|
+
applyGroupDrawerShortcuts(hidden)
|
|
1163
|
+
return true
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
function renderGroupDrawerEditor() {
|
|
1167
|
+
const options = $('group-drawer-shortcut-options')
|
|
1168
|
+
const rows = [...$('group-drawer').querySelectorAll('[data-drawer-shortcut]')].map(shortcut => {
|
|
1169
|
+
const row = document.createElement('label')
|
|
1170
|
+
const name = document.createElement('span')
|
|
1171
|
+
const checkbox = document.createElement('input')
|
|
1172
|
+
row.className = 'group-drawer-toggle'
|
|
1173
|
+
name.textContent = t(shortcut.dataset.i18nAria)
|
|
1174
|
+
checkbox.type = 'checkbox'
|
|
1175
|
+
checkbox.checked = !shortcut.hidden
|
|
1176
|
+
checkbox.dataset.drawerShortcutSetting = shortcut.dataset.drawerShortcut
|
|
1177
|
+
row.append(shortcut.querySelector('svg').cloneNode(true), name, checkbox)
|
|
1178
|
+
return row
|
|
1179
|
+
})
|
|
1180
|
+
options.replaceChildren(...rows)
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
const GROUP_DRAWER_PREVIEW_LIMIT = 6
|
|
1184
|
+
let groupDrawerPreviewRead = null
|
|
1185
|
+
|
|
1186
|
+
function isGroupDrawerPanel(name) {
|
|
1187
|
+
return groupDrawerOpen() && $('group-drawer').dataset.panel === name
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
async function renderGroupDrawerNewSession() {
|
|
1191
|
+
const connection = captureConnection()
|
|
1192
|
+
const preview = new AbortController()
|
|
1193
|
+
groupDrawerPreviewRead = preview
|
|
1194
|
+
const current = () => isGroupDrawerPanel('new') && connection.valid() && groupDrawerPreviewRead === preview
|
|
1195
|
+
const form = $('group-drawer-new-form')
|
|
1196
|
+
const status = $('group-drawer-new-status')
|
|
1197
|
+
form.hidden = true
|
|
1198
|
+
status.hidden = false
|
|
1199
|
+
$('group-drawer-new-connect').hidden = !!connection.token
|
|
1200
|
+
status.textContent = t(connection.token ? 'session.loading' : 'groups.drawerConnectFirst')
|
|
1201
|
+
if (!connection.token) return
|
|
1202
|
+
form.append($('new-session-card'))
|
|
1203
|
+
try {
|
|
1204
|
+
if (!await prepareNewSessionForm('', current)) return
|
|
1205
|
+
status.hidden = true
|
|
1206
|
+
form.hidden = false
|
|
1207
|
+
} catch {
|
|
1208
|
+
if (current()) status.textContent = t('groups.drawerPreviewFailed')
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
function groupDrawerPreviewRow(title, meta, icon = '') {
|
|
1213
|
+
return `<div class="group-drawer-preview-row">${icon}<div class="group-drawer-option-copy">
|
|
1214
|
+
<span class="group-drawer-option-name" title="${esc(title)}">${esc(title)}</span>
|
|
1215
|
+
<span class="group-drawer-option-meta">${esc(meta)}</span>
|
|
1216
|
+
</div></div>`
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
async function readGroupDrawerPreview(name, url, headers, render) {
|
|
1220
|
+
const status = $('group-drawer-' + name + '-status')
|
|
1221
|
+
const list = $('group-drawer-' + name + '-list')
|
|
1222
|
+
const connection = captureConnection()
|
|
1223
|
+
list.replaceChildren()
|
|
1224
|
+
status.textContent = t(connection.token ? 'session.loading' : 'groups.drawerConnectFirst')
|
|
1225
|
+
if (!connection.token) return
|
|
1226
|
+
const controller = new AbortController()
|
|
1227
|
+
groupDrawerPreviewRead = controller
|
|
1228
|
+
const current = () => groupDrawerPreviewRead === controller && !controller.signal.aborted && connection.valid() && isGroupDrawerPanel(name)
|
|
1229
|
+
try {
|
|
1230
|
+
const response = await fetch(url, { headers, signal: AbortSignal.any([controller.signal, AbortSignal.timeout(15000)]) })
|
|
1231
|
+
if (!response.ok) throw Error('preview request failed')
|
|
1232
|
+
const data = await response.json()
|
|
1233
|
+
if (current()) render(data, list, status)
|
|
1234
|
+
} catch {
|
|
1235
|
+
if (current()) status.textContent = t('groups.drawerPreviewFailed')
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
function renderGroupDrawerFiles() {
|
|
1240
|
+
const path = $('group-drawer-files-path')
|
|
1241
|
+
path.hidden = true
|
|
1242
|
+
const workspace = workspaceById(state.fs.workspaceId)
|
|
1243
|
+
const target = (state.fs.loaded && state.fs.path) || workspace?.path || ''
|
|
1244
|
+
void readGroupDrawerPreview('files', fsApiUrl('/list', { path: target }), fsHeaders(), (data, list, status) => {
|
|
1245
|
+
if (!Array.isArray(data.entries)) throw Error('invalid file list')
|
|
1246
|
+
path.textContent = data.path || target
|
|
1247
|
+
path.hidden = !path.textContent
|
|
1248
|
+
status.textContent = t(data.entries.length ? 'groups.drawerFileCount' : 'fs.emptyDir', { n: data.entries.length })
|
|
1249
|
+
list.innerHTML = data.entries.slice(0, GROUP_DRAWER_PREVIEW_LIMIT).map(entry => {
|
|
1250
|
+
const isDir = entry.type === 'dir'
|
|
1251
|
+
return groupDrawerPreviewRow(entry.name, isDir ? t('fs.dir') : fmtSize(entry.size), fsIconSvg(isDir))
|
|
1252
|
+
}).join('')
|
|
1253
|
+
})
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
function renderGroupDrawerPlugins() {
|
|
1257
|
+
const config = optionalPluginConfig()
|
|
1258
|
+
void readGroupDrawerPreview('plugins', config.url('/remote/api/plugins/state'), config.headers, (data, list, status) => {
|
|
1259
|
+
if (data.ok !== true || !Array.isArray(data.items)) throw Error('invalid plugin state')
|
|
1260
|
+
const plugins = data.items.filter(item => item?.name).sort((a, b) => Number(!!b.enabled) - Number(!!a.enabled))
|
|
1261
|
+
status.textContent = t(plugins.length ? 'groups.drawerPluginCount' : 'groups.drawerNoPlugins', { n: plugins.length })
|
|
1262
|
+
list.innerHTML = plugins.slice(0, GROUP_DRAWER_PREVIEW_LIMIT).map(item => {
|
|
1263
|
+
const stateLabel = t(item.enabled ? 'groups.drawerPluginEnabled' : 'groups.drawerPluginDisabled')
|
|
1264
|
+
const meta = item.version ? item.version + ' · ' + stateLabel : stateLabel
|
|
1265
|
+
return groupDrawerPreviewRow(item.displayName || item.name, meta)
|
|
1266
|
+
}).join('')
|
|
1267
|
+
})
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
function renderGroupDrawerOperations() {
|
|
1271
|
+
if (!isGroupDrawerPanel('operations')) return
|
|
1272
|
+
const pending = [
|
|
1273
|
+
...state.approvals.map(item => ({ sessionId: item.sessionId, title: t('pending.approvalTitle', { tool: item.toolName || t('tool.default') }) })),
|
|
1274
|
+
...state.questions.map(item => ({ sessionId: item.sessionId, title: item.questions?.[0]?.question || t('notify.questionTitle') })),
|
|
1275
|
+
]
|
|
1276
|
+
const receipts = window.DshOperations?.pending().length || 0
|
|
1277
|
+
$('group-drawer-pending-summary').textContent = t(pending.length ? 'pending.count' : 'pending.empty', { n: pending.length })
|
|
1278
|
+
$('group-drawer-receipts-summary').textContent = t(receipts ? 'groups.drawerReceipts' : 'groups.drawerNoReceipts', { n: receipts })
|
|
1279
|
+
$('group-drawer-pending-list').innerHTML = pending.slice(0, GROUP_DRAWER_PREVIEW_LIMIT)
|
|
1280
|
+
.map(item => groupDrawerPreviewRow(item.title, titleOf(state.byId.get(item.sessionId)))).join('')
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
function renderGroupDrawerSettings() {
|
|
1284
|
+
const rows = [...$('settings-home').querySelectorAll('[data-settings-group], #btn-host-schedule')].filter(row => !row.hidden)
|
|
1285
|
+
$('group-drawer-settings-list').innerHTML = rows.map(row => {
|
|
1286
|
+
const target = row.dataset.settingsGroup
|
|
1287
|
+
const title = row.querySelector('.setting-name')?.textContent || row.textContent.trim()
|
|
1288
|
+
const description = row.querySelector('.setting-desc')?.textContent || ''
|
|
1289
|
+
return `<button type="button" class="group-drawer-preview-row" ${target ? `data-drawer-setting="${esc(target)}"` : 'data-drawer-view="view-schedule"'}>
|
|
1290
|
+
<span class="group-drawer-option-copy"><span class="group-drawer-option-name">${esc(title)}</span>
|
|
1291
|
+
${description ? `<span class="group-drawer-option-meta">${esc(description)}</span>` : ''}</span>
|
|
1292
|
+
<span aria-hidden="true">›</span></button>`
|
|
1293
|
+
}).join('')
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
function renderGroupDrawerVersion() {
|
|
1297
|
+
const version = activeGatewayHealth()?.version
|
|
1298
|
+
$('group-drawer-gateway-version').textContent = version ? 'v' + version : '—'
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
function setGroupDrawerPanel(name, moveFocus = true) {
|
|
1302
|
+
const drawer = $('group-drawer')
|
|
1303
|
+
const previous = drawer.dataset.panel || ''
|
|
1304
|
+
if (previous !== name) {
|
|
1305
|
+
groupDrawerPreviewRead?.abort()
|
|
1306
|
+
groupDrawerPreviewRead = null
|
|
1307
|
+
if (['new', 'search'].includes(previous) && customSelectCurrent?.select.closest('[data-drawer-panel]')?.dataset.drawerPanel === previous) {
|
|
1308
|
+
closeCustomSelect({ restoreFocus: false })
|
|
1309
|
+
}
|
|
1310
|
+
if (previous === 'new') $('modal-new-session').append($('new-session-card'))
|
|
1311
|
+
}
|
|
1312
|
+
let active
|
|
1313
|
+
let previousTrigger
|
|
1314
|
+
for (const button of drawer.querySelectorAll('[data-drawer-open-panel]')) {
|
|
1315
|
+
const key = button.dataset.drawerOpenPanel
|
|
1316
|
+
button.setAttribute('aria-expanded', String(key === name))
|
|
1317
|
+
if (key === name) active = button
|
|
1318
|
+
if (key === previous) previousTrigger = button
|
|
1319
|
+
}
|
|
1320
|
+
drawer.dataset.panel = active ? name : ''
|
|
1321
|
+
$('group-drawer-panel').hidden = !active
|
|
1322
|
+
for (const section of drawer.querySelectorAll('[data-drawer-panel]')) {
|
|
1323
|
+
section.hidden = section.dataset.drawerPanel !== drawer.dataset.panel
|
|
1324
|
+
}
|
|
1325
|
+
if (!active) {
|
|
1326
|
+
if (moveFocus) previousTrigger?.focus({ preventScroll: true })
|
|
1327
|
+
return
|
|
1328
|
+
}
|
|
1329
|
+
const title = $('group-drawer-panel-title')
|
|
1330
|
+
title.textContent = t(active.dataset.i18nAria)
|
|
1331
|
+
drawer.querySelector('.group-drawer-body').scrollTop = 0
|
|
1332
|
+
if (name === 'recent') renderGroupDrawerSessions()
|
|
1333
|
+
if (name === 'groups') renderGroupDrawer()
|
|
1334
|
+
if (name === 'edit') renderGroupDrawerEditor()
|
|
1335
|
+
if (name === 'search') refreshDrawerSearch()
|
|
1336
|
+
if (name === 'new') void renderGroupDrawerNewSession()
|
|
1337
|
+
if (name === 'files') renderGroupDrawerFiles()
|
|
1338
|
+
if (name === 'operations') renderGroupDrawerOperations()
|
|
1339
|
+
if (name === 'plugins') renderGroupDrawerPlugins()
|
|
1340
|
+
if (name === 'settings') renderGroupDrawerSettings()
|
|
1341
|
+
if (name === 'version') renderGroupDrawerVersion()
|
|
1342
|
+
if (moveFocus) title.focus({ preventScroll: true })
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
function backGroupDrawer() {
|
|
1346
|
+
if ($('group-drawer').dataset.panel) setGroupDrawerPanel('')
|
|
1347
|
+
else closeGroupDrawer()
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1011
1350
|
function openGroupDrawer() {
|
|
1012
1351
|
const drawer = $('group-drawer')
|
|
1013
1352
|
const backdrop = $('group-drawer-backdrop')
|
|
1014
1353
|
const trigger = $('group-drawer-trigger')
|
|
1015
1354
|
if (!drawer || !backdrop || !trigger) return
|
|
1016
|
-
|
|
1017
|
-
groupDrawerReturnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : trigger
|
|
1355
|
+
groupDrawerReturnFocus = document.activeElement === $('btn-session-more') ? document.activeElement : trigger
|
|
1018
1356
|
drawer.classList.remove('hidden')
|
|
1019
1357
|
backdrop.classList.remove('hidden')
|
|
1020
1358
|
document.body.classList.add('group-drawer-open')
|
|
1021
1359
|
trigger.setAttribute('aria-expanded', 'true')
|
|
1022
|
-
|
|
1360
|
+
applyGroupDrawerShortcuts(readGroupDrawerHiddenShortcuts())
|
|
1361
|
+
setGroupDrawerPanel('', false)
|
|
1362
|
+
drawer.querySelector('.group-drawer-icons').scrollTop = 0
|
|
1363
|
+
requestAnimationFrame(() => {
|
|
1364
|
+
if (groupDrawerOpen()) $('group-drawer-close')?.focus({ preventScroll: true })
|
|
1365
|
+
})
|
|
1023
1366
|
}
|
|
1024
1367
|
|
|
1025
1368
|
function closeGroupDrawer({ restoreFocus = true } = {}) {
|
|
@@ -1027,24 +1370,27 @@ function closeGroupDrawer({ restoreFocus = true } = {}) {
|
|
|
1027
1370
|
const backdrop = $('group-drawer-backdrop')
|
|
1028
1371
|
const trigger = $('group-drawer-trigger')
|
|
1029
1372
|
if (!drawer || !backdrop || drawer.classList.contains('hidden')) return
|
|
1373
|
+
setGroupDrawerPanel('', false)
|
|
1030
1374
|
drawer.classList.add('hidden')
|
|
1031
1375
|
backdrop.classList.add('hidden')
|
|
1032
1376
|
document.body.classList.remove('group-drawer-open')
|
|
1033
1377
|
trigger?.setAttribute('aria-expanded', 'false')
|
|
1034
1378
|
if (restoreFocus) (groupDrawerReturnFocus || trigger)?.focus({ preventScroll: true })
|
|
1035
1379
|
groupDrawerReturnFocus = null
|
|
1380
|
+
groupDrawerRoute = null
|
|
1036
1381
|
}
|
|
1037
1382
|
|
|
1038
1383
|
function keepGroupDrawerFocus(event) {
|
|
1039
|
-
if (!groupDrawerOpen()) return
|
|
1384
|
+
if (!groupDrawerOpen() || customSelectCurrent) return
|
|
1040
1385
|
if (event.key === 'Escape') {
|
|
1041
1386
|
event.preventDefault()
|
|
1042
|
-
|
|
1387
|
+
backGroupDrawer()
|
|
1043
1388
|
return
|
|
1044
1389
|
}
|
|
1045
1390
|
if (event.key !== 'Tab') return
|
|
1046
1391
|
const drawer = $('group-drawer')
|
|
1047
|
-
const targets = [...drawer.querySelectorAll('button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])')]
|
|
1392
|
+
const targets = [...drawer.querySelectorAll('button:not([disabled]), input:not([disabled]), [href], [tabindex]:not([tabindex="-1"])')]
|
|
1393
|
+
.filter(element => element.getClientRects().length)
|
|
1048
1394
|
if (!targets.length) return
|
|
1049
1395
|
const first = targets[0]
|
|
1050
1396
|
const last = targets[targets.length - 1]
|
|
@@ -1356,7 +1702,8 @@ function clearReconnect() {
|
|
|
1356
1702
|
|
|
1357
1703
|
function openStreams() {
|
|
1358
1704
|
if (!state.token) return
|
|
1359
|
-
|
|
1705
|
+
void refreshConnectionHealth()
|
|
1706
|
+
if (state.streamMode === 'poll' && !pollTimer && navigator.onLine) startPolling()
|
|
1360
1707
|
openStream('mux', onMuxFrame, true)
|
|
1361
1708
|
openStream('host', onHostFrame, false)
|
|
1362
1709
|
}
|
|
@@ -1436,10 +1783,10 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1436
1783
|
state.approvals = []
|
|
1437
1784
|
state.questions = []
|
|
1438
1785
|
renderPending()
|
|
1786
|
+
resyncAfterStreamOpen()
|
|
1439
1787
|
}
|
|
1440
1788
|
if (refreshOnOpen) refreshAll()
|
|
1441
1789
|
if (allStreamsOpen()) {
|
|
1442
|
-
resyncAfterStreamOpen()
|
|
1443
1790
|
void pingServer(state.server || location.origin)
|
|
1444
1791
|
void refreshHostDescription()
|
|
1445
1792
|
}
|
|
@@ -1469,6 +1816,7 @@ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
|
|
|
1469
1816
|
aggregateStreamFailures()
|
|
1470
1817
|
updateConn()
|
|
1471
1818
|
if (!navigator.onLine) { clearReconnect(); return }
|
|
1819
|
+
if (kind === 'mux') scheduleSessionSync()
|
|
1472
1820
|
// 任一通道连续失败 3 次就降级轮询;另一个通道不会清零它的失败计数。
|
|
1473
1821
|
if (state.streamMode !== 'poll' && meta.failures >= 3) { enterPollMode(); return }
|
|
1474
1822
|
// 多服务器: 连续掉线若干次就重测速, 自动换到当前可达的最快地址
|
|
@@ -1505,6 +1853,7 @@ function enterPollMode() {
|
|
|
1505
1853
|
function stopPolling() {
|
|
1506
1854
|
pollInFlight?.stop()
|
|
1507
1855
|
pollInFlight = null
|
|
1856
|
+
delete state.pollSeq.muxReady
|
|
1508
1857
|
clearInterval(pollTimer); pollTimer = null
|
|
1509
1858
|
clearInterval(wsRetryTimer); wsRetryTimer = null
|
|
1510
1859
|
}
|
|
@@ -1546,12 +1895,15 @@ async function pollKind(kind, cancellation) {
|
|
|
1546
1895
|
result=await read(signal)
|
|
1547
1896
|
}
|
|
1548
1897
|
res=result.res;data=result.data
|
|
1549
|
-
} catch {
|
|
1550
|
-
if (!valid()) return
|
|
1551
|
-
if (res.status === 401) { authFailure(); return }
|
|
1552
|
-
if (!res.ok) return
|
|
1898
|
+
} catch {}
|
|
1553
1899
|
if (!valid()) return
|
|
1554
|
-
|
|
1900
|
+
const received = !!res?.ok && Array.isArray(data?.events)
|
|
1901
|
+
if (kind === 'mux' && !!cursors.muxReady !== received) {
|
|
1902
|
+
cursors.muxReady = received
|
|
1903
|
+
updateConn()
|
|
1904
|
+
}
|
|
1905
|
+
if (res?.status === 401) { authFailure(); return }
|
|
1906
|
+
if (!received) return
|
|
1555
1907
|
// 网关重启或客户端离线过久后,游标可能落后于内存环形缓冲;
|
|
1556
1908
|
// 从当前缓冲重新接收,并刷新权威会话列表,避免静默漏事件。
|
|
1557
1909
|
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)
|
|
@@ -1624,7 +1976,8 @@ document.addEventListener('visibilitychange', () => {
|
|
|
1624
1976
|
})
|
|
1625
1977
|
window.addEventListener('pageshow', onResume)
|
|
1626
1978
|
setInterval(() => {
|
|
1627
|
-
if (document.visibilityState === 'visible' && state.token) {
|
|
1979
|
+
if (document.visibilityState === 'visible' && state.token && navigator.onLine) {
|
|
1980
|
+
void refreshConnectionHealth()
|
|
1628
1981
|
repairMissingStreams()
|
|
1629
1982
|
sessionSyncTick()
|
|
1630
1983
|
}
|
|
@@ -1636,6 +1989,7 @@ setInterval(() => {
|
|
|
1636
1989
|
|
|
1637
1990
|
/* 网络感知: 离线立刻关 WS + 显示离线, 在线立即重连 */
|
|
1638
1991
|
window.addEventListener('offline', () => {
|
|
1992
|
+
connectionHealthProbe = null
|
|
1639
1993
|
clearReconnect()
|
|
1640
1994
|
closeStream('mux')
|
|
1641
1995
|
closeStream('host')
|
|
@@ -1662,6 +2016,7 @@ navigator.connection?.addEventListener?.('change',()=>{
|
|
|
1662
2016
|
function onMuxFrame(full) {
|
|
1663
2017
|
const f = full.payload
|
|
1664
2018
|
if (!f) return
|
|
2019
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.handleFrame?.(full)
|
|
1665
2020
|
if (f.type === 'session/reasoning') {
|
|
1666
2021
|
if (f.sessionId === state.current) { applyReasoningBaseline(f.partialReasoning); scheduleReasoningRender() }
|
|
1667
2022
|
return
|
|
@@ -1680,24 +2035,40 @@ function onMuxFrame(full) {
|
|
|
1680
2035
|
state.questions = state.questions.filter(q => q.rpcId !== full.rpcId)
|
|
1681
2036
|
state.questions.push({ ...f, rpcId: full.rpcId })
|
|
1682
2037
|
notifyPendingRequest(full, t('notify.questionTitle'), f.questions?.map(q => q.question).join(' / ') || t('notify.questionBody'))
|
|
1683
|
-
renderPending(); return
|
|
2038
|
+
renderPending(); if (typeof refreshPlanReview === 'function') refreshPlanReview(); return
|
|
1684
2039
|
}
|
|
1685
2040
|
if (f.type === 'question/resolved') {
|
|
1686
2041
|
clearPendingNotification(f)
|
|
1687
2042
|
state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId)
|
|
1688
2043
|
if (state.questionModal?.rpcId === f.questionRpcId) { $('modal-question').classList.add('hidden'); state.questionModal = null }
|
|
1689
|
-
renderPending(); return
|
|
2044
|
+
renderPending(); if (typeof refreshPlanReview === 'function') refreshPlanReview(); return
|
|
2045
|
+
}
|
|
2046
|
+
if (f.type === 'session/queue') {
|
|
2047
|
+
if (hostQueue?.accept(f.sessionId, f.seq) !== false) state.queues[f.sessionId] = f.items || []
|
|
2048
|
+
renderQueue(); return
|
|
1690
2049
|
}
|
|
1691
|
-
if (f.type === 'session/queue') { state.queues[f.sessionId] = f.items || []; renderQueue(); return }
|
|
1692
2050
|
if (f.type === 'session/jobs') { state.jobs[f.sessionId] = f.jobs || []; renderJobs(); return }
|
|
1693
|
-
if (f.type === 'session/projection') {
|
|
2051
|
+
if (f.type === 'session/projection') {
|
|
2052
|
+
applyProjection(f.sessionId, f.key, f.value, f.seq)
|
|
2053
|
+
if (f.key === 'plan' && f.sessionId === state.current && typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
2054
|
+
if (f.key === 'conversationContinuation' && f.sessionId === state.current) renderHistory()
|
|
2055
|
+
if (f.key === 'agentTeam') window.DshSubagents?.updateTeam?.(f.sessionId, f.value, f.seq)
|
|
2056
|
+
return
|
|
2057
|
+
}
|
|
1694
2058
|
if (f.type === 'stream/error') { toast(t('stream.error', { msg: f.error?.message || '' }), 'err') }
|
|
1695
2059
|
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') }
|
|
1696
2060
|
}
|
|
1697
2061
|
function onHostFrame(full) {
|
|
1698
2062
|
const f = full.payload
|
|
1699
2063
|
if (!f) return
|
|
2064
|
+
if (f.type === 'host/relay-activation') { void syncRelayActivation(f.activationId); return }
|
|
2065
|
+
if (f.type === 'schedule/changed') { void hostSchedule?.refresh(true); return }
|
|
1700
2066
|
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)
|
|
2067
|
+
if (f.type === 'host/pinned-sessions-changed') {
|
|
2068
|
+
state.wbPinned = Array.isArray(f.pinnedSessionIds) ? f.pinnedSessionIds : []
|
|
2069
|
+
renderSessions()
|
|
2070
|
+
return
|
|
2071
|
+
}
|
|
1701
2072
|
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()
|
|
1702
2073
|
if (f.type === 'host/session-activity') {
|
|
1703
2074
|
const session = state.byId.get(f.sessionId)
|
|
@@ -1708,7 +2079,7 @@ function onHostFrame(full) {
|
|
|
1708
2079
|
if (f.type === 'host/session-status') {
|
|
1709
2080
|
if (f.running && state.runtimeErrors?.delete(f.sessionId) && state.current === f.sessionId) renderHistory()
|
|
1710
2081
|
const s = state.byId.get(f.sessionId)
|
|
1711
|
-
if (s) { s.running = f.running; if (f.running) s.error = false; if (state.current === f.sessionId) { renderSessionCards(); updateCancelBtn(); renderSessionSub(); updateSessionStatus() } }
|
|
2082
|
+
if (s) { s.running = f.running; if (f.running) s.error = false; if (state.current === f.sessionId) { renderSessionCards(); updateCancelBtn(); renderSessionSub(); updateSessionStatus(); renderQueue() } }
|
|
1712
2083
|
if (!f.running) scheduleSessionSync(f.sessionId)
|
|
1713
2084
|
return
|
|
1714
2085
|
}
|
|
@@ -1843,6 +2214,8 @@ function observeCompactionEvent(sessionId, event, meta = {}) {
|
|
|
1843
2214
|
|
|
1844
2215
|
function onSessionEvent(sessionId, event, meta = {}) {
|
|
1845
2216
|
if (!event) return
|
|
2217
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.handleEvent?.(sessionId, event)
|
|
2218
|
+
if (typeof turnDiffController !== 'undefined') turnDiffController?.handleEvent?.(sessionId, event)
|
|
1846
2219
|
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)
|
|
1847
2220
|
const s = state.byId.get(sessionId)
|
|
1848
2221
|
observeCompactionEvent(sessionId, event, meta)
|
|
@@ -1867,6 +2240,7 @@ function onSessionEvent(sessionId, event, meta = {}) {
|
|
|
1867
2240
|
if (state.current === sessionId) renderSessionTitle()
|
|
1868
2241
|
}
|
|
1869
2242
|
if (state.current === sessionId) insertLiveEvent(event)
|
|
2243
|
+
if (['plan/mode', 'tool/call', 'tool/result'].includes(event.type) && typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
1870
2244
|
if (['goal/created', 'goal/updated', 'goal/completed', 'goal/cleared', 'todo/updated', 'plan/updated', 'checkpoint/created'].includes(event.type)) scheduleRefresh()
|
|
1871
2245
|
}
|
|
1872
2246
|
|
|
@@ -1914,6 +2288,7 @@ async function refreshSessions() {
|
|
|
1914
2288
|
if(typeof window!=='undefined')window.DshDoctorEntry?.consumeSessionLink(openSession,state.byId)
|
|
1915
2289
|
renderSessions()
|
|
1916
2290
|
refreshWorkbench()
|
|
2291
|
+
if (typeof sessionManager !== 'undefined') sessionManager?.hydrate?.()
|
|
1917
2292
|
}
|
|
1918
2293
|
|
|
1919
2294
|
function removeLocalSessionRecord(sessionId) {
|
|
@@ -2050,9 +2425,11 @@ function rememberRuntimeError(sessionId, message) {
|
|
|
2050
2425
|
if (sessionId === state.current) { renderHistory(); scheduleSessionSync(sessionId) }
|
|
2051
2426
|
}
|
|
2052
2427
|
function resyncAfterStreamOpen() {
|
|
2428
|
+
if (typeof hostSchedule !== 'undefined') void hostSchedule?.refresh(true)
|
|
2053
2429
|
if (!state.current || Date.now() - state.lastStreamResyncAt < 1200) return
|
|
2054
2430
|
state.lastStreamResyncAt = Date.now()
|
|
2055
|
-
|
|
2431
|
+
if (typeof hostQueue !== 'undefined') hostQueue?.reconnect()
|
|
2432
|
+
scheduleSessionSync(state.current, 0)
|
|
2056
2433
|
}
|
|
2057
2434
|
function sessionTitleValue(s) {
|
|
2058
2435
|
const value = proj(s, 'title', '')
|
|
@@ -2105,8 +2482,12 @@ function setGoalCollapsed(sessionId, goal, collapsed) {
|
|
|
2105
2482
|
|
|
2106
2483
|
function updatePendingBadge() {
|
|
2107
2484
|
const pending = state.approvals.length + state.questions.length
|
|
2108
|
-
|
|
2109
|
-
|
|
2485
|
+
for (const id of ['nav-pending', 'group-drawer-pending']) {
|
|
2486
|
+
const badge = $(id)
|
|
2487
|
+
if (!badge) continue
|
|
2488
|
+
badge.classList.toggle('hidden', pending === 0)
|
|
2489
|
+
badge.textContent = pending || ''
|
|
2490
|
+
}
|
|
2110
2491
|
}
|
|
2111
2492
|
|
|
2112
2493
|
/* ---------------- 工作台与归档会话 ---------------- */
|
|
@@ -2174,7 +2555,10 @@ function orderedWorkspaceItems(items) {
|
|
|
2174
2555
|
}
|
|
2175
2556
|
function orderedWorkspaceSessions(workspaceId, items) {
|
|
2176
2557
|
const { value } = workbenchOrderScopeValue()
|
|
2177
|
-
|
|
2558
|
+
const pinned = new Set(state.wbPinned || [])
|
|
2559
|
+
const ordered = orderedItems(items, value.sessionIds?.[String(workspaceId)], item => item.sessionId)
|
|
2560
|
+
// Host pinning outranks the client-side manual order in every grouped view.
|
|
2561
|
+
return ordered.sort((a, b) => Number(pinned.has(b.sessionId)) - Number(pinned.has(a.sessionId)))
|
|
2178
2562
|
}
|
|
2179
2563
|
function saveWorkbenchOrder(mutator) {
|
|
2180
2564
|
const { store, value } = workbenchOrderScopeValue()
|
|
@@ -2244,7 +2628,7 @@ function renderWorkspaceNavigation() {
|
|
|
2244
2628
|
}
|
|
2245
2629
|
const selectedWorkspace = workspaceById(state.workspaceFilter)
|
|
2246
2630
|
const pathBox = $('session-workspace-path')
|
|
2247
|
-
if (pathBox) pathBox.textContent = selectedWorkspace?.path ||
|
|
2631
|
+
if (pathBox) pathBox.textContent = selectedWorkspace?.path || ''
|
|
2248
2632
|
const filesButton = $('session-workspace-files')
|
|
2249
2633
|
if (filesButton) filesButton.disabled = !selectedWorkspace
|
|
2250
2634
|
|
|
@@ -2289,10 +2673,12 @@ async function refreshWorkbench({ discover = false } = {}) {
|
|
|
2289
2673
|
if (!valid()) return
|
|
2290
2674
|
if (value) state.wbProjects = Array.isArray(value.items) ? value.items : []
|
|
2291
2675
|
if (value) state.wbArchived = Array.isArray(value.archivedSessionIds) ? value.archivedSessionIds : []
|
|
2676
|
+
if (value) state.wbPinned = Array.isArray(value.pinnedSessionIds) ? value.pinnedSessionIds : []
|
|
2292
2677
|
} catch {
|
|
2293
2678
|
if (!valid()) return
|
|
2294
2679
|
state.wbProjects = []
|
|
2295
2680
|
state.wbArchived = []
|
|
2681
|
+
state.wbPinned = []
|
|
2296
2682
|
}
|
|
2297
2683
|
// 以磁盘实际目录为准同步工作台项目:删除目录后不再残留,新增子目录自动收纳。
|
|
2298
2684
|
if (discover && state.wb?.bound && state.wb.path) {
|
|
@@ -2328,6 +2714,7 @@ async function refreshWorkbench({ discover = false } = {}) {
|
|
|
2328
2714
|
renderWorkspaceNavigation()
|
|
2329
2715
|
renderWorkbench()
|
|
2330
2716
|
renderSessions()
|
|
2717
|
+
if (typeof sessionManager !== 'undefined') sessionManager?.hydrate?.()
|
|
2331
2718
|
}
|
|
2332
2719
|
function renderWorkbench() {
|
|
2333
2720
|
const bar = $('workbench-bar')
|
|
@@ -2429,20 +2816,25 @@ function commitWorkspaceGroupOrder(order) {
|
|
|
2429
2816
|
}
|
|
2430
2817
|
function sortedSessions() {
|
|
2431
2818
|
const items = topLevelSessions()
|
|
2819
|
+
const pinned = new Set(state.wbPinned || [])
|
|
2820
|
+
const pinRank = session => pinned.has(session.sessionId) ? 0 : 1
|
|
2432
2821
|
if (state.sessionSort === 'workspace') {
|
|
2433
2822
|
return items.sort((a, b) => {
|
|
2823
|
+
const byPin = pinRank(a) - pinRank(b)
|
|
2824
|
+
if (byPin) return byPin
|
|
2434
2825
|
const aw = sessionCwd(a) || '\uffff'
|
|
2435
2826
|
const bw = sessionCwd(b) || '\uffff'
|
|
2436
2827
|
const byWorkspace = aw.localeCompare(bw, undefined, { numeric: true, sensitivity: 'base' })
|
|
2437
2828
|
return byWorkspace || (sessionSortTime(b) - sessionSortTime(a))
|
|
2438
2829
|
})
|
|
2439
2830
|
}
|
|
2440
|
-
return items.sort((a, b) => sessionSortTime(b) - sessionSortTime(a))
|
|
2831
|
+
return items.sort((a, b) => pinRank(a) - pinRank(b) || sessionSortTime(b) - sessionSortTime(a))
|
|
2441
2832
|
}
|
|
2442
2833
|
function renderSessions() {
|
|
2443
2834
|
const list = $('session-list')
|
|
2444
2835
|
const allItems = sortedSessions()
|
|
2445
2836
|
const archivedSet = new Set(state.wbArchived || [])
|
|
2837
|
+
const pinnedSet = new Set(state.wbPinned || [])
|
|
2446
2838
|
const visible = allItems.filter(s => {
|
|
2447
2839
|
if (!state.workspaceFilter) return true
|
|
2448
2840
|
if (state.workspaceFilter === WORKSPACE_UNGROUPED) return !workspaceForSession(s)
|
|
@@ -2455,6 +2847,7 @@ function renderSessions() {
|
|
|
2455
2847
|
const workspace = sessionWorkspaceLabel(s)
|
|
2456
2848
|
const workspaceTitle = sessionWorkspaceName(s)
|
|
2457
2849
|
const title = sessionLabelOf(s)
|
|
2850
|
+
const isPinned = pinnedSet.has(s.sessionId)
|
|
2458
2851
|
const goal = goalOf(s)
|
|
2459
2852
|
const pending = (state.approvals.some(a => a.sessionId === s.sessionId) || state.questions.some(q => q.sessionId === s.sessionId)) ? 'pending' : ''
|
|
2460
2853
|
const queueN = (state.queues[s.sessionId] || []).filter(i => i.placement === 'queued').length
|
|
@@ -2463,18 +2856,22 @@ function renderSessions() {
|
|
|
2463
2856
|
if (pending) dots.push('pending')
|
|
2464
2857
|
const badge = goal ? `<span class="sc-badge ${goal.phase === 'active' ? 'goal-active' : ''}">${esc(t('sessions.goalBadge', { phase: goal.phase || '?' }))}</span>` : ''
|
|
2465
2858
|
const queueBadge = queueN ? `<span class="sc-badge">${esc(t('sessions.queueBadge', { n: queueN }))}</span>` : ''
|
|
2466
|
-
const archiveButton = archivedSet.has(s.sessionId)
|
|
2859
|
+
const archiveButton = archivedSet.has(s.sessionId)
|
|
2860
|
+
? `<button type="button" class="sc-archive-btn" data-unarchive-session="${esc(s.sessionId)}">${esc(t('session.unarchive'))}</button>`
|
|
2861
|
+
: `<button type="button" class="sc-archive-btn" data-archive-session="${esc(s.sessionId)}">${esc(t('session.archive'))}</button>`
|
|
2467
2862
|
return `<div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}" role="button" tabindex="0" aria-label="${esc(sessionLabelOf(s))}">
|
|
2468
2863
|
<div class="session-card ${state.current === s.sessionId ? 'current' : ''}">
|
|
2469
|
-
<div class="sc-title">${esc(title)}</div>
|
|
2864
|
+
<div class="sc-title">${isPinned ? '<span class="sc-pin" aria-label="' + esc(t('sessions.pinned')) + '">📌</span> ' : ''}${esc(title)}</div>
|
|
2470
2865
|
<div class="sc-meta">
|
|
2471
|
-
<span class="sc-
|
|
2866
|
+
<span class="sc-workspace" title="${esc(workspace)}">${esc(workspaceTitle)}</span>
|
|
2472
2867
|
<span>${fmtTime(sessionSortTime(s))}</span>
|
|
2868
|
+
</div>
|
|
2869
|
+
${dots.length || badge || queueBadge ? `<div class="sc-status">
|
|
2870
|
+
${dots.length ? `<span class="sc-dot ${dots.join(' ')}"></span>` : ''}
|
|
2473
2871
|
${s.running ? '<span>' + t('sessions.running') + '</span>' : ''}
|
|
2474
2872
|
${badge}${queueBadge}
|
|
2475
|
-
</div
|
|
2476
|
-
<
|
|
2477
|
-
<span class="sc-arrow">›</span>
|
|
2873
|
+
</div>` : ''}
|
|
2874
|
+
<span class="sc-arrow" aria-hidden="true">›</span>
|
|
2478
2875
|
</div>
|
|
2479
2876
|
${archiveButton}
|
|
2480
2877
|
</div>`
|
|
@@ -2524,6 +2921,7 @@ function renderSessions() {
|
|
|
2524
2921
|
<div class="stat pending"><div class="v">${pending}</div><div class="k">${t('sessions.statPending')}</div></div>
|
|
2525
2922
|
<div class="stat ctx"><div class="v">${visible.length}</div><div class="k">${t('sessions.statTotal')}</div></div>`
|
|
2526
2923
|
updatePendingBadge()
|
|
2924
|
+
renderGroupDrawerSessions()
|
|
2527
2925
|
}
|
|
2528
2926
|
|
|
2529
2927
|
/* ---------------- 会话详情 ---------------- */
|
|
@@ -2580,6 +2978,8 @@ async function openSession(id) {
|
|
|
2580
2978
|
}
|
|
2581
2979
|
cancelHistoryLoad()
|
|
2582
2980
|
state.current = id
|
|
2981
|
+
if (typeof syncComposerToolsScope === 'function') syncComposerToolsScope()
|
|
2982
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.setSession?.(id)
|
|
2583
2983
|
setSessionRecovery('loading')
|
|
2584
2984
|
state.history = emptyHistory()
|
|
2585
2985
|
const openingHistory=state.history, openingConnection=captureConnection()
|
|
@@ -2595,6 +2995,7 @@ async function openSession(id) {
|
|
|
2595
2995
|
$('history').innerHTML = '<div class="empty">' + t('history.loading') + '</div>'
|
|
2596
2996
|
renderQueue()
|
|
2597
2997
|
renderSessionPending()
|
|
2998
|
+
if (typeof hostQueue !== 'undefined') hostQueue?.reconnect()
|
|
2598
2999
|
void refreshCompactionStatus(id)
|
|
2599
3000
|
getConversationView().reset()
|
|
2600
3001
|
try { const restored=await restoreCachedHistory();globalThis.DshDiagnostics?.record('history.cache',{phase:restored?'hit':'miss',sessionId:id}) } catch(error) {
|
|
@@ -2643,6 +3044,10 @@ async function closeSession() {
|
|
|
2643
3044
|
const connection=captureConnection(),discard=!wasLoading&&shouldDiscardEmptySession(sessionId)
|
|
2644
3045
|
state.current = null
|
|
2645
3046
|
if (typeof updateContextRing === 'function') updateContextRing()
|
|
3047
|
+
if (typeof syncComposerToolsScope === 'function') syncComposerToolsScope()
|
|
3048
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.setSession?.(null)
|
|
3049
|
+
if (typeof turnDiffController !== 'undefined') turnDiffController?.setSession?.(null)
|
|
3050
|
+
if (typeof planReviewHost !== 'undefined') planReviewHost?.classList.add('hidden')
|
|
2646
3051
|
state.history = emptyHistory()
|
|
2647
3052
|
document.body.classList.remove('in-session')
|
|
2648
3053
|
showView('view-home')
|
|
@@ -2670,9 +3075,10 @@ function bindNativeBack() {
|
|
|
2670
3075
|
try {
|
|
2671
3076
|
CAP.Plugins?.App?.addListener?.('appStateChange',({isActive})=>{if(isActive)onResume()})
|
|
2672
3077
|
CAP.Plugins?.App?.addListener?.('backButton', () => {
|
|
3078
|
+
if (typeof window !== 'undefined' && window.DshSlashSuggestions?.close()) return
|
|
2673
3079
|
if ($('composer-wrap')?.classList.contains('fs')) { setComposerFullscreen(false); return }
|
|
2674
3080
|
if (customSelectCurrent) { closeCustomSelect(); return }
|
|
2675
|
-
if (groupDrawerOpen()) {
|
|
3081
|
+
if (groupDrawerOpen()) { backGroupDrawer(); return }
|
|
2676
3082
|
if (typeof window !== 'undefined' && window.DshImagePreview?.closeSaveMenu?.()) return
|
|
2677
3083
|
if (typeof window !== 'undefined' && window.DshImagePreview?.isOpen?.()) { window.DshImagePreview.close(); return }
|
|
2678
3084
|
if (typeof window !== 'undefined' && window.DshExtensions?.closeShortcuts(true)) return
|
|
@@ -3049,20 +3455,7 @@ function insertLiveEvent(event) {
|
|
|
3049
3455
|
scheduleHistoryCacheSave()
|
|
3050
3456
|
}
|
|
3051
3457
|
|
|
3052
|
-
function isToolEvent(type) { return type === 'tool/call' || type === 'tool/result' }
|
|
3053
|
-
|
|
3054
|
-
/** One collapsed row for a turn's tools and reasoning, matching the desktop conversation rhythm. */
|
|
3055
|
-
function activityGroupHtml(group, ctx) {
|
|
3056
|
-
const items = group.items || []
|
|
3057
|
-
if (!items.length) return ''
|
|
3058
|
-
const tools = items.filter(item => item.kind === 'tool').map(item => item.entry)
|
|
3059
|
-
const running = !!group.running
|
|
3060
|
-
const failed = tools.some(entry => entry.view?.toolActivity?.error || entry.event?.data?.error)
|
|
3061
|
-
const body = items.map(item => item.kind === 'reasoning'
|
|
3062
|
-
? window.DshActivity.reasoning({ text: item.text, key: item.key })
|
|
3063
|
-
: eventHtml(item.entry, ctx)).join('')
|
|
3064
|
-
return `<details class="chat-activity-group${failed ? ' is-error' : ''}${running ? ' is-running' : ''}" data-activity-key="activity-group:${items[0]?.seq ?? ''}"><summary><span class="activity-group-title">${esc(t('activity.group', { n: items.length }))}</span>${running ? `<span class="activity-group-live"><i aria-hidden="true"></i>${esc(t('activity.groupRunning'))}</span>` : ''}<span class="activity-chevron" aria-hidden="true"></span></summary><div class="activity-group-body">${body}</div></details>`
|
|
3065
|
-
}
|
|
3458
|
+
function isToolEvent(type) { return window.DshActivity?.isToolEvent?.(type) ?? (type === 'tool/call' || type === 'tool/result') }
|
|
3066
3459
|
|
|
3067
3460
|
function filteredEntries() {
|
|
3068
3461
|
const showTools = LS.get('showTools', '1') !== '0'
|
|
@@ -3096,6 +3489,7 @@ function bindTurnResultActions() {
|
|
|
3096
3489
|
if (!state.byId.has(id)) {
|
|
3097
3490
|
const branch = { ...parent, projections: parent?.projections ? { ...JSON.parse(JSON.stringify(parent.projections)), asOfSeq: 0 } : undefined,
|
|
3098
3491
|
sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
|
|
3492
|
+
if (branch.projections?.values) delete branch.projections.values.conversationContinuation
|
|
3099
3493
|
state.byId.set(id, branch)
|
|
3100
3494
|
state.sessions.unshift(branch)
|
|
3101
3495
|
renderSessions()
|
|
@@ -3115,24 +3509,48 @@ function renderHistory(reset=false,mode='auto') {
|
|
|
3115
3509
|
if(weakStreamTrim())prepared=prepared.filter(entry=>entry.event?.type!=='tool/call'||entry.view?.toolActivity)
|
|
3116
3510
|
// DSH 0.2.1 also embeds tool blocks in messages; the separated events own the grouped rows.
|
|
3117
3511
|
state.history.suppressBlockTools = state.history.visible.some(entry => entry.event?.type === 'tool/call')
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3512
|
+
const activity = window.DshActivity
|
|
3513
|
+
const groupLive = activity?.group && !weakStreamTrim()
|
|
3514
|
+
if(activity?.group)prepared=activity.group(prepared, {
|
|
3515
|
+
liveReasoning: groupLive ? [...state.history.partialReasoning.values()] : [],
|
|
3516
|
+
running: !!state.byId.get(state.current)?.running,
|
|
3517
|
+
suppressBlockTools: state.history.suppressBlockTools,
|
|
3518
|
+
showTools: LS.get('showTools', '1') !== '0',
|
|
3519
|
+
})
|
|
3126
3520
|
if (window.DshTurnResults) {
|
|
3127
3521
|
prepared = window.DshTurnResults.decorate(prepared, state.history.visible, { sessionId: state.current, canFork: canForkTurnResult() })
|
|
3128
3522
|
bindTurnResultActions()
|
|
3129
3523
|
}
|
|
3524
|
+
if (typeof turnDiffController !== 'undefined' && turnDiffController) {
|
|
3525
|
+
turnDiffController.setLayout('mobile')
|
|
3526
|
+
turnDiffController.setSession(state.current)
|
|
3527
|
+
if (typeof turnDiffHtmlFor === 'function') prepared = prepared.map(entry => ({ ...entry, view: { ...entry.view, turnDiffHtml: turnDiffHtmlFor(entry) } }))
|
|
3528
|
+
}
|
|
3529
|
+
if (activity?.withContinuation && activeGatewayCapability('sessionContinuation') === true) {
|
|
3530
|
+
const sessionId = state.current, history = state.history, connection = captureConnection()
|
|
3531
|
+
const session = state.byId.get(sessionId)
|
|
3532
|
+
prepared = activity.withContinuation($('history'), prepared, {
|
|
3533
|
+
history, ending: session && session.origin !== 'subagent' && session.formatStatus !== 'migration-required'
|
|
3534
|
+
&& !(state.wbArchived || []).includes(sessionId)
|
|
3535
|
+
? proj(session, 'conversationContinuation') : undefined,
|
|
3536
|
+
valid: () => connection.valid() && state.current === sessionId && state.history === history,
|
|
3537
|
+
render: () => renderHistory(),
|
|
3538
|
+
submit: ending => rpc('session.continue', { sessionId, ending }),
|
|
3539
|
+
failed: error => {
|
|
3540
|
+
if (error.operationPending) notifyPendingOperation(error, connection)
|
|
3541
|
+
else if (connection.valid() && state.current === sessionId && state.history === history) {
|
|
3542
|
+
toast(error.message, 'err'); void resyncCurrentSession()
|
|
3543
|
+
}
|
|
3544
|
+
},
|
|
3545
|
+
})
|
|
3546
|
+
}
|
|
3130
3547
|
if(window.DshActivity?.groupFailures)prepared=window.DshActivity.groupFailures(prepared)
|
|
3131
3548
|
const hostError = state.runtimeErrors?.get(state.current)
|
|
3132
3549
|
const recordedError = state.history.visible.some(entry => window.DshActivity?.failure?.(entry.event)?.message === hostError)
|
|
3133
3550
|
const runtimeHtml = hostError && !recordedError ? window.DshActivity?.failureHtml?.(hostError) || '' : ''
|
|
3134
|
-
getConversationView().set(prepared,{reset,follow:mode==='bottom',live:partialReasoningHtml()+runtimeHtml,hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('history.empty')})
|
|
3551
|
+
getConversationView().set(prepared,{reset,follow:mode==='bottom',live:(groupLive?'':partialReasoningHtml())+runtimeHtml,hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('history.empty')})
|
|
3135
3552
|
window.DshImagePreview?.hydrate?.($('history'))
|
|
3553
|
+
if (typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
3136
3554
|
}
|
|
3137
3555
|
window.applyStreamPreference=()=>{if(state.current)renderHistory(false,'auto')}
|
|
3138
3556
|
|
|
@@ -3191,13 +3609,14 @@ function bindRail() {
|
|
|
3191
3609
|
const INTERESTING_EVENTS = new Set([
|
|
3192
3610
|
'turn/start', 'turn/end',
|
|
3193
3611
|
'user/message', 'assistant/message', 'assistant/attempt',
|
|
3194
|
-
'tool/call', 'tool/result',
|
|
3612
|
+
'tool/call', 'tool/result', 'tool/ptc-dispatch-start', 'tool/ptc-dispatch',
|
|
3195
3613
|
'agent/status',
|
|
3196
3614
|
'checkpoint/created', 'compaction/complete', 'compaction/summary',
|
|
3197
3615
|
'goal/created', 'goal/updated', 'goal/completed', 'goal/cleared',
|
|
3198
3616
|
'todo/updated', 'plan/updated',
|
|
3199
3617
|
'question/asked', 'question/resolved',
|
|
3200
|
-
'approval/asked', 'approval/resolved'
|
|
3618
|
+
'approval/asked', 'approval/resolved',
|
|
3619
|
+
'deliverables/presented', 'workspace/changes'
|
|
3201
3620
|
])
|
|
3202
3621
|
function messageSource(data) {
|
|
3203
3622
|
const source = data?.source ?? data?.message?.source
|
|
@@ -3231,12 +3650,15 @@ function eventHtml(entry, ctx = {}) {
|
|
|
3231
3650
|
const ev = entry.event || {}
|
|
3232
3651
|
const data = ev.data || {}
|
|
3233
3652
|
const type = ev.type || 'event'
|
|
3234
|
-
const failure = window.DshActivity?.failureHtml?.(window.DshActivity.failure(ev)) || ''
|
|
3653
|
+
const failure = window.DshActivity?.failureHtml?.(window.DshActivity.failure(ev), false, entry.view?.continuation) || ''
|
|
3235
3654
|
if (entry.view?.turnResult) return failure + window.DshTurnResults.html(entry.view.turnResult)
|
|
3236
3655
|
// Successful boundaries stay quiet; failed turns keep their durable explanation.
|
|
3237
|
-
if (type === 'turn/start'
|
|
3656
|
+
if (type === 'turn/start') return failure
|
|
3657
|
+
if (type === 'turn/end') return failure + (entry.view?.turnDiffHtml || '')
|
|
3658
|
+
if (type === 'deliverables/presented' || type === 'workspace/changes') return ''
|
|
3238
3659
|
if (type === 'assistant/attempt') return window.DshActivity?.attemptHtml?.(ev) || ''
|
|
3239
|
-
if (entry.view?.
|
|
3660
|
+
if (entry.view?.activityTurn) return window.DshActivity.turnHtml(entry.view.activityTurn)
|
|
3661
|
+
if (entry.view?.activityGroup) return window.DshActivity.groupHtml(entry.view.activityGroup, item => eventHtml(item, ctx))
|
|
3240
3662
|
if (!shouldShowEvent(type, ev)) return ''
|
|
3241
3663
|
if (window.DshActivity && isToolEvent(type)) return window.DshActivity.toolEvent(entry)
|
|
3242
3664
|
let inner = ''
|
|
@@ -3467,7 +3889,7 @@ async function interruptSubagent(childId, parentId = state.current) {
|
|
|
3467
3889
|
const result = await safeRpc('subagent.interrupt', { parentSessionId: parentId, childSessionId: childId, mode: 'continuable' }, t('subagent.interruptFailed'))
|
|
3468
3890
|
if (result == null || !connection.valid() || state.current !== rootId) return
|
|
3469
3891
|
toast(t('subagent.interruptSubmitted'), 'ok')
|
|
3470
|
-
|
|
3892
|
+
return true
|
|
3471
3893
|
}
|
|
3472
3894
|
|
|
3473
3895
|
/* ---------------- 发送 / 取消 / 快捷菜单 ---------------- */
|
|
@@ -3703,6 +4125,16 @@ async function sendSessionText(text) {
|
|
|
3703
4125
|
}
|
|
3704
4126
|
|
|
3705
4127
|
let composerSending = false
|
|
4128
|
+
let composerTools = null
|
|
4129
|
+
let sessionSearchController = null
|
|
4130
|
+
let sessionSearchMount = null
|
|
4131
|
+
let sessionSearchConnection = null
|
|
4132
|
+
let sessionManager = null
|
|
4133
|
+
let workspaceAdminMount = null
|
|
4134
|
+
let planReviewController = null
|
|
4135
|
+
let planReviewHost = null
|
|
4136
|
+
let turnDiffController = null
|
|
4137
|
+
let turnDiffRoot = null
|
|
3706
4138
|
const composerSendFeedback = new Map()
|
|
3707
4139
|
const steeringInFlight = new Set()
|
|
3708
4140
|
function composerContext() { return `${state.server}\0${state.current}` }
|
|
@@ -3753,7 +4185,9 @@ async function sendPrompt(payload, context) {
|
|
|
3753
4185
|
if (error.operationPending) {
|
|
3754
4186
|
// Keep the warning on screen instead of a 3-second toast while the
|
|
3755
4187
|
// connection is unchanged; otherwise attribute it to the old connection.
|
|
3756
|
-
if (connection.valid() && composerContext() === context)
|
|
4188
|
+
if (connection.valid() && composerContext() === context) {
|
|
4189
|
+
setComposerSendFeedback(context, error.receiptMissing ? 'send.receiptMissing' : 'send.resultUnconfirmed', 'unknown')
|
|
4190
|
+
}
|
|
3757
4191
|
else notifyPendingOperation(error, connection)
|
|
3758
4192
|
return null
|
|
3759
4193
|
}
|
|
@@ -3912,17 +4346,25 @@ async function encodeComposerImagesFor(images) {
|
|
|
3912
4346
|
|
|
3913
4347
|
async function sendMessage(requestedMode) {
|
|
3914
4348
|
const input = $('composer-input')
|
|
4349
|
+
if (typeof window !== 'undefined') window.DshSlashSuggestions?.close()
|
|
3915
4350
|
const originalText = input.value
|
|
3916
|
-
const
|
|
4351
|
+
const clean = originalText.trim()
|
|
4352
|
+
// Quoted selections are composed into the same user message as Markdown
|
|
4353
|
+
// blockquotes; the Host receives one ordinary prompt and sees no client-made
|
|
4354
|
+
// approval/reference side channel. A slash command keeps its leading token.
|
|
4355
|
+
const quoted = clean && !clean.startsWith('/') && typeof composerTools !== 'undefined' ? composerTools?.quotes() || [] : []
|
|
4356
|
+
const quoteText = quoted.length ? window.DshComposerTools.formatQuotes(quoted) : ''
|
|
4357
|
+
const text = [quoteText, clean].filter(Boolean).join('\n\n')
|
|
3917
4358
|
const context = composerContext()
|
|
3918
4359
|
const images = state.composerImages.slice()
|
|
3919
4360
|
if ((!text && !images.length) || !state.current) return
|
|
3920
|
-
if (images.length &&
|
|
4361
|
+
if (images.length && clean.startsWith('/')) { toast(t('composer.imageSlashUnsupported'), 'err'); return }
|
|
3921
4362
|
const mode = typeof requestedMode === 'string' ? requestedMode : composerSendMode()
|
|
3922
4363
|
if (await sendSessionContent(text, images, mode) && composerContext() === context) {
|
|
3923
4364
|
if (input.value === originalText) { input.value = ''; autosize(input) }
|
|
3924
|
-
if (typeof composerDrafts !== 'undefined' && composerDrafts.get(state.current) ===
|
|
4365
|
+
if (typeof composerDrafts !== 'undefined' && composerDrafts.get(state.current) === originalText) composerDrafts.delete(state.current)
|
|
3925
4366
|
if (state.composerImages.length === images.length && images.every((item, i) => item === state.composerImages[i])) clearComposerImages()
|
|
4367
|
+
if (quoted.length) composerTools?.clearQuotes(quoted.map(quote => quote.id))
|
|
3926
4368
|
}
|
|
3927
4369
|
}
|
|
3928
4370
|
|
|
@@ -3931,6 +4373,485 @@ function hideComposerMenu() {
|
|
|
3931
4373
|
$('btn-plus').classList.remove('active')
|
|
3932
4374
|
}
|
|
3933
4375
|
|
|
4376
|
+
/* ---------------- B/C 输入、搜索与管理 ---------------- */
|
|
4377
|
+
function bcEnglish() { return I18N.lang === 'en' }
|
|
4378
|
+
function bcText(zh, en) { return bcEnglish() ? en : zh }
|
|
4379
|
+
|
|
4380
|
+
async function bcRpc(method, payload, options = {}) {
|
|
4381
|
+
return rpc(method, payload, Number.isFinite(options.timeoutMs) ? options.timeoutMs : 45000, options.signal || null)
|
|
4382
|
+
}
|
|
4383
|
+
|
|
4384
|
+
function composerToolsHost() {
|
|
4385
|
+
return {
|
|
4386
|
+
scope: () => ({ key: JSON.stringify([connectionGeneration, state.current]), sessionId: state.current || '', connection: captureConnection() }),
|
|
4387
|
+
async listReferences(scope, query) {
|
|
4388
|
+
const sessionId = scope?.sessionId || state.current
|
|
4389
|
+
if (!sessionId) return null
|
|
4390
|
+
const [files, sessions] = await Promise.allSettled([
|
|
4391
|
+
bcRpc('fileReferences.list', { sessionId, query: String(query || '') }, { timeoutMs: 12000 }),
|
|
4392
|
+
bcRpc('sessionReferenceResolver.candidates', { sessionId, query: String(query || '') }, { timeoutMs: 12000 }),
|
|
4393
|
+
])
|
|
4394
|
+
if (files.status !== 'fulfilled' && sessions.status !== 'fulfilled') return null
|
|
4395
|
+
const references = []
|
|
4396
|
+
if (files.status === 'fulfilled' && Array.isArray(files.value)) {
|
|
4397
|
+
for (const row of files.value) {
|
|
4398
|
+
const insert = window.DshComposerTools.fileReferenceMention(row)
|
|
4399
|
+
if (!insert) continue
|
|
4400
|
+
references.push({
|
|
4401
|
+
insert,
|
|
4402
|
+
label: row?.kind === 'directory' ? String(row?.path || '') + '/' : String(row?.path || ''),
|
|
4403
|
+
detail: row?.kind === 'directory' ? bcText('目录', 'Directory') : bcText('文件', 'File'),
|
|
4404
|
+
kind: 'file',
|
|
4405
|
+
allowed: true,
|
|
4406
|
+
})
|
|
4407
|
+
}
|
|
4408
|
+
}
|
|
4409
|
+
if (sessions.status === 'fulfilled' && Array.isArray(sessions.value)) {
|
|
4410
|
+
for (const row of sessions.value) {
|
|
4411
|
+
if (typeof row?.mention !== 'string' || !row.mention.startsWith('@')) continue
|
|
4412
|
+
references.push({
|
|
4413
|
+
insert: row.mention,
|
|
4414
|
+
label: row.displayTitle || row.label || row.sessionId || '',
|
|
4415
|
+
detail: row.cwd || '',
|
|
4416
|
+
kind: 'session',
|
|
4417
|
+
allowed: true,
|
|
4418
|
+
})
|
|
4419
|
+
}
|
|
4420
|
+
}
|
|
4421
|
+
return { supported: true, references }
|
|
4422
|
+
},
|
|
4423
|
+
notice: (text, kind) => toast(text, kind === 'err' ? 'err' : ''),
|
|
4424
|
+
}
|
|
4425
|
+
}
|
|
4426
|
+
|
|
4427
|
+
let quoteSelectionButton = null
|
|
4428
|
+
function selectedMessageQuote() {
|
|
4429
|
+
const selection = window.getSelection?.()
|
|
4430
|
+
if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null
|
|
4431
|
+
const range = selection.getRangeAt(0)
|
|
4432
|
+
const history = $('history')
|
|
4433
|
+
if (!history || !range.commonAncestorContainer) return null
|
|
4434
|
+
const startNode = range.startContainer.nodeType === 3 ? range.startContainer.parentElement : range.startContainer
|
|
4435
|
+
const endNode = range.endContainer.nodeType === 3 ? range.endContainer.parentElement : range.endContainer
|
|
4436
|
+
const startMessage = startNode?.closest?.('.msg')
|
|
4437
|
+
const endMessage = endNode?.closest?.('.msg')
|
|
4438
|
+
if (!startMessage || !endMessage || startMessage !== endMessage || !history.contains(startMessage)) return null
|
|
4439
|
+
const text = selection.toString().replace(/\r\n?/g, '\n').trim()
|
|
4440
|
+
if (!text) return null
|
|
4441
|
+
const role = startMessage.classList.contains('user') ? 'user' : startMessage.classList.contains('assistant') ? 'assistant' : ''
|
|
4442
|
+
const messageId = startMessage.dataset.seq || ''
|
|
4443
|
+
const rect = range.getBoundingClientRect()
|
|
4444
|
+
return { text, role, messageId, rect }
|
|
4445
|
+
}
|
|
4446
|
+
|
|
4447
|
+
function hideQuoteSelectionButton() {
|
|
4448
|
+
if (!quoteSelectionButton) return
|
|
4449
|
+
quoteSelectionButton.hidden = true
|
|
4450
|
+
quoteSelectionButton.classList.add('hidden')
|
|
4451
|
+
}
|
|
4452
|
+
|
|
4453
|
+
function updateQuoteSelectionButton() {
|
|
4454
|
+
if (!quoteSelectionButton || !composerTools) return
|
|
4455
|
+
const selected = selectedMessageQuote()
|
|
4456
|
+
if (!selected) { hideQuoteSelectionButton(); return }
|
|
4457
|
+
const rect = selected.rect
|
|
4458
|
+
const x = Math.max(8, Math.min(window.innerWidth - 150, rect.left + rect.width / 2 - 70))
|
|
4459
|
+
const y = Math.max(8, Math.min(window.innerHeight - 56, rect.bottom + 8))
|
|
4460
|
+
quoteSelectionButton.style.left = x + 'px'
|
|
4461
|
+
quoteSelectionButton.style.top = y + 'px'
|
|
4462
|
+
quoteSelectionButton.hidden = false
|
|
4463
|
+
quoteSelectionButton.classList.remove('hidden')
|
|
4464
|
+
quoteSelectionButton.dataset.ready = '1'
|
|
4465
|
+
}
|
|
4466
|
+
|
|
4467
|
+
function initQuoteSelection() {
|
|
4468
|
+
if (quoteSelectionButton) return
|
|
4469
|
+
quoteSelectionButton = document.createElement('button')
|
|
4470
|
+
quoteSelectionButton.type = 'button'
|
|
4471
|
+
quoteSelectionButton.className = 'ct-quote-pick hidden'
|
|
4472
|
+
quoteSelectionButton.hidden = true
|
|
4473
|
+
quoteSelectionButton.textContent = t('composer.quoteSelection')
|
|
4474
|
+
quoteSelectionButton.addEventListener('pointerdown', event => event.preventDefault())
|
|
4475
|
+
quoteSelectionButton.addEventListener('click', event => {
|
|
4476
|
+
event.preventDefault()
|
|
4477
|
+
const selected = selectedMessageQuote()
|
|
4478
|
+
hideQuoteSelectionButton()
|
|
4479
|
+
if (!selected || !composerTools) return
|
|
4480
|
+
composerTools.addQuote({ messageId: selected.messageId, role: selected.role, text: selected.text })
|
|
4481
|
+
window.getSelection?.()?.removeAllRanges?.()
|
|
4482
|
+
toast(t('composer.quoteAdded'), 'ok')
|
|
4483
|
+
})
|
|
4484
|
+
document.body.append(quoteSelectionButton)
|
|
4485
|
+
document.addEventListener('selectionchange', () => {
|
|
4486
|
+
if (document.activeElement === $('composer-input')) return
|
|
4487
|
+
updateQuoteSelectionButton()
|
|
4488
|
+
})
|
|
4489
|
+
window.addEventListener('scroll', hideQuoteSelectionButton, { passive: true })
|
|
4490
|
+
window.addEventListener('resize', hideQuoteSelectionButton)
|
|
4491
|
+
}
|
|
4492
|
+
|
|
4493
|
+
function initComposerToolsUi() {
|
|
4494
|
+
if (composerTools || !window.DshComposerTools) return
|
|
4495
|
+
const input = $('composer-input')
|
|
4496
|
+
const composer = input?.closest?.('.composer')
|
|
4497
|
+
const wrap = $('composer-wrap')
|
|
4498
|
+
if (!input || !composer || !wrap) return
|
|
4499
|
+
const anchor = document.createElement('div')
|
|
4500
|
+
anchor.className = 'ct-anchor'
|
|
4501
|
+
const menu = document.createElement('div')
|
|
4502
|
+
menu.id = 'composer-tools-menu'
|
|
4503
|
+
menu.className = 'ct-menu hidden'
|
|
4504
|
+
menu.hidden = true
|
|
4505
|
+
anchor.append(menu)
|
|
4506
|
+
const quotes = document.createElement('div')
|
|
4507
|
+
quotes.id = 'composer-tools-quotes'
|
|
4508
|
+
quotes.className = 'ct-quotes hidden'
|
|
4509
|
+
quotes.hidden = true
|
|
4510
|
+
const hint = document.createElement('p')
|
|
4511
|
+
hint.id = 'composer-tools-hint'
|
|
4512
|
+
hint.className = 'ct-hint hidden'
|
|
4513
|
+
hint.hidden = true
|
|
4514
|
+
composer.before(anchor)
|
|
4515
|
+
composer.before(quotes)
|
|
4516
|
+
composer.before(hint)
|
|
4517
|
+
composerTools = window.DshComposerTools.create({
|
|
4518
|
+
input,
|
|
4519
|
+
menu,
|
|
4520
|
+
hint,
|
|
4521
|
+
quoteList: quotes,
|
|
4522
|
+
host: composerToolsHost(),
|
|
4523
|
+
commands: false,
|
|
4524
|
+
onChange: () => autosize(input),
|
|
4525
|
+
})
|
|
4526
|
+
initQuoteSelection()
|
|
4527
|
+
}
|
|
4528
|
+
|
|
4529
|
+
function syncComposerToolsScope() {
|
|
4530
|
+
composerTools?.setScope?.({ key: JSON.stringify([connectionGeneration, state.current]), sessionId: state.current || '', connection: captureConnection() })
|
|
4531
|
+
}
|
|
4532
|
+
|
|
4533
|
+
function sessionSearchAdapter() {
|
|
4534
|
+
return {
|
|
4535
|
+
rpc: bcRpc,
|
|
4536
|
+
sessions: () => (state.sessions || []).filter(s => s && s.sessionId && s.origin !== 'subagent' && s.blank !== true),
|
|
4537
|
+
workspaces: () => workspaceItems(),
|
|
4538
|
+
archivedSessionIds: () => state.wbArchived || [],
|
|
4539
|
+
pinnedSessionIds: () => state.wbPinned || [],
|
|
4540
|
+
titleOf: session => titleOf(session),
|
|
4541
|
+
historyRoot: () => $('history'),
|
|
4542
|
+
openSession: async (sessionId) => {
|
|
4543
|
+
closeGroupDrawer({ restoreFocus: false })
|
|
4544
|
+
await openSession(sessionId)
|
|
4545
|
+
},
|
|
4546
|
+
notice: (message) => toast(message),
|
|
4547
|
+
}
|
|
4548
|
+
}
|
|
4549
|
+
|
|
4550
|
+
function initSessionSearchUi() {
|
|
4551
|
+
if (!window.DshSessionSearch) return
|
|
4552
|
+
$('group-drawer-search')?.classList.remove('hidden')
|
|
4553
|
+
}
|
|
4554
|
+
|
|
4555
|
+
function refreshDrawerSearch() {
|
|
4556
|
+
if (!sessionSearchConnection?.valid()) {
|
|
4557
|
+
sessionSearchController?.cancelSearch()
|
|
4558
|
+
sessionSearchMount?.destroy()
|
|
4559
|
+
sessionSearchConnection = captureConnection()
|
|
4560
|
+
sessionSearchController = window.DshSessionSearch.init(sessionSearchAdapter())
|
|
4561
|
+
sessionSearchMount = window.DshSessionSearch.mount($('session-search-host'), sessionSearchController, {
|
|
4562
|
+
enhanceWorkspaceSelect: enhanceCustomSelect,
|
|
4563
|
+
})
|
|
4564
|
+
}
|
|
4565
|
+
sessionSearchController.syncCatalog()
|
|
4566
|
+
sessionSearchMount?.refresh()
|
|
4567
|
+
}
|
|
4568
|
+
|
|
4569
|
+
function workspaceRemovalConfirmation(request) {
|
|
4570
|
+
const impact = request?.impact || {}
|
|
4571
|
+
const lines = [
|
|
4572
|
+
bcText(`移除工作区登记「${request?.displayTitle || impact.name || ''}」?`, `Remove the workspace registration "${request?.displayTitle || impact.name || ''}"?`),
|
|
4573
|
+
bcText('只删除工作区登记,不删除磁盘目录、文件或会话历史。', 'Only the Workspace registration is removed; directories, files and conversation history stay on disk.'),
|
|
4574
|
+
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.`),
|
|
4575
|
+
]
|
|
4576
|
+
return window.confirm(lines.join('\n\n'))
|
|
4577
|
+
}
|
|
4578
|
+
|
|
4579
|
+
function promptWorkspaceTitle({ workspace, current }) {
|
|
4580
|
+
const value = window.prompt(t('workspace.renamePrompt'), current || workspace?.title || '')
|
|
4581
|
+
return value == null ? null : String(value)
|
|
4582
|
+
}
|
|
4583
|
+
|
|
4584
|
+
function initSessionManagementUi() {
|
|
4585
|
+
if (sessionManager || !window.DshSessionManagement) return
|
|
4586
|
+
sessionManager = window.DshSessionManagement.init({
|
|
4587
|
+
rpc: bcRpc,
|
|
4588
|
+
sessions: () => state.sessions,
|
|
4589
|
+
workspaces: () => workspaceItems(),
|
|
4590
|
+
archivedSessionIds: () => state.wbArchived || [],
|
|
4591
|
+
pinnedSessionIds: () => state.wbPinned || [],
|
|
4592
|
+
titleOf: session => titleOf(session),
|
|
4593
|
+
refresh: async () => { await Promise.all([refreshWorkbench(), refreshSessions()]) },
|
|
4594
|
+
confirm: workspaceRemovalConfirmation,
|
|
4595
|
+
promptTitle: promptWorkspaceTitle,
|
|
4596
|
+
toast,
|
|
4597
|
+
})
|
|
4598
|
+
const manageButton = document.createElement('button')
|
|
4599
|
+
manageButton.id = 'btn-manage-workspaces'
|
|
4600
|
+
manageButton.type = 'button'
|
|
4601
|
+
manageButton.className = 'mini-btn'
|
|
4602
|
+
manageButton.textContent = t('workspace.manage')
|
|
4603
|
+
$('session-workspace-files')?.after(manageButton)
|
|
4604
|
+
manageButton.addEventListener('click', openWorkspaceAdmin)
|
|
4605
|
+
const dialog = $('session-actions')
|
|
4606
|
+
if (dialog) {
|
|
4607
|
+
const box = document.createElement('div')
|
|
4608
|
+
box.id = 'session-admin-actions'
|
|
4609
|
+
dialog.querySelector('#btn-archive-session')?.before(box)
|
|
4610
|
+
window.DshSessionManagement.bindWorkspaceAdmin(box, sessionManager, {
|
|
4611
|
+
onResult: result => { if (result?.ok) renderSessions() },
|
|
4612
|
+
})
|
|
4613
|
+
}
|
|
4614
|
+
updateBcControlLabels()
|
|
4615
|
+
}
|
|
4616
|
+
|
|
4617
|
+
function ensureWorkspaceAdminModal() {
|
|
4618
|
+
let modal = $('modal-workspace-admin')
|
|
4619
|
+
if (modal) return modal
|
|
4620
|
+
modal = document.createElement('div')
|
|
4621
|
+
modal.id = 'modal-workspace-admin'
|
|
4622
|
+
modal.className = 'modal hidden'
|
|
4623
|
+
modal.setAttribute('role', 'dialog')
|
|
4624
|
+
modal.setAttribute('aria-modal', 'true')
|
|
4625
|
+
modal.setAttribute('aria-labelledby', 'workspace-admin-title')
|
|
4626
|
+
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>`
|
|
4627
|
+
document.body.append(modal)
|
|
4628
|
+
const close = () => modal.classList.add('hidden')
|
|
4629
|
+
modal.addEventListener('click', event => {
|
|
4630
|
+
if (event.target === modal || event.target.closest('[data-workspace-admin-close]')) close()
|
|
4631
|
+
})
|
|
4632
|
+
modal.querySelector('[data-workspace-admin-close]').textContent = t('modal.close')
|
|
4633
|
+
modal.querySelector('#workspace-admin-title').textContent = t('workspace.manage')
|
|
4634
|
+
return modal
|
|
4635
|
+
}
|
|
4636
|
+
|
|
4637
|
+
function openWorkspaceAdmin() {
|
|
4638
|
+
if (!sessionManager) return
|
|
4639
|
+
const modal = ensureWorkspaceAdminModal()
|
|
4640
|
+
sessionManager.hydrate()
|
|
4641
|
+
if (!workspaceAdminMount) {
|
|
4642
|
+
workspaceAdminMount = window.DshSessionManagement.mountWorkspaceAdmin($('workspace-admin-host'), sessionManager, {
|
|
4643
|
+
promptTitle: promptWorkspaceTitle,
|
|
4644
|
+
onResult: result => { if (result?.ok) { renderSessions(); workspaceAdminMount?.refresh() } },
|
|
4645
|
+
})
|
|
4646
|
+
} else workspaceAdminMount.refresh()
|
|
4647
|
+
modal.querySelector('#workspace-admin-title').textContent = t('workspace.manage')
|
|
4648
|
+
modal.querySelector('[data-workspace-admin-close]').textContent = t('modal.close')
|
|
4649
|
+
modal.classList.remove('hidden')
|
|
4650
|
+
}
|
|
4651
|
+
|
|
4652
|
+
function refreshSessionAdminActions() {
|
|
4653
|
+
const box = $('session-admin-actions')
|
|
4654
|
+
const session = state.byId.get(state.current)
|
|
4655
|
+
if (!box || !sessionManager || !session) return
|
|
4656
|
+
box.innerHTML = window.DshSessionManagement.renderSessionAdminActions(session, sessionManager.getState())
|
|
4657
|
+
}
|
|
4658
|
+
|
|
4659
|
+
async function unarchiveSessionFromList(sessionId) {
|
|
4660
|
+
if (!sessionManager) return
|
|
4661
|
+
await sessionManager.unarchive(sessionId)
|
|
4662
|
+
renderSessions()
|
|
4663
|
+
}
|
|
4664
|
+
|
|
4665
|
+
function updateBcControlLabels() {
|
|
4666
|
+
const manage = $('btn-manage-workspaces')
|
|
4667
|
+
if (manage) manage.textContent = t('workspace.manage')
|
|
4668
|
+
if (quoteSelectionButton) quoteSelectionButton.textContent = t('composer.quoteSelection')
|
|
4669
|
+
const modal = $('modal-workspace-admin')
|
|
4670
|
+
if (modal) {
|
|
4671
|
+
modal.querySelector('#workspace-admin-title').textContent = t('workspace.manage')
|
|
4672
|
+
modal.querySelector('[data-workspace-admin-close]').textContent = t('modal.close')
|
|
4673
|
+
}
|
|
4674
|
+
}
|
|
4675
|
+
|
|
4676
|
+
function initBcFeatures() {
|
|
4677
|
+
initComposerToolsUi()
|
|
4678
|
+
initSessionSearchUi()
|
|
4679
|
+
initSessionManagementUi()
|
|
4680
|
+
initReviewFeatures()
|
|
4681
|
+
syncComposerToolsScope()
|
|
4682
|
+
}
|
|
4683
|
+
|
|
4684
|
+
function isPlanReviewQuestion(question) {
|
|
4685
|
+
return !!window.DshPlanReview?.planReviewOf?.(question?.questions)
|
|
4686
|
+
}
|
|
4687
|
+
|
|
4688
|
+
function planReviewSnapshot(sessionId) {
|
|
4689
|
+
const session = state.byId.get(sessionId)
|
|
4690
|
+
const plan = session?.projections?.values?.plan
|
|
4691
|
+
return {
|
|
4692
|
+
plan,
|
|
4693
|
+
questions: (state.questions || []).filter(frame => String(frame?.sessionId || '') === String(sessionId || '')),
|
|
4694
|
+
connected: !!state.streamsOk?.mux,
|
|
4695
|
+
readOnly: false,
|
|
4696
|
+
capability: plan === undefined ? undefined : true,
|
|
4697
|
+
}
|
|
4698
|
+
}
|
|
4699
|
+
|
|
4700
|
+
function updatePlanReviewVisibility(view) {
|
|
4701
|
+
if (!planReviewHost) return
|
|
4702
|
+
const visible = !!(view?.plan?.supported || view?.review || (Array.isArray(view?.plans) && view.plans.length)
|
|
4703
|
+
|| (state.current && state.history.loaded))
|
|
4704
|
+
planReviewHost.classList.toggle('hidden', !visible)
|
|
4705
|
+
}
|
|
4706
|
+
|
|
4707
|
+
function refreshPlanReview() {
|
|
4708
|
+
if (!planReviewController) return
|
|
4709
|
+
let view = null
|
|
4710
|
+
try { view = planReviewController.render() } catch {}
|
|
4711
|
+
updatePlanReviewVisibility(view)
|
|
4712
|
+
return view
|
|
4713
|
+
}
|
|
4714
|
+
|
|
4715
|
+
function turnDiffEnabled() {
|
|
4716
|
+
return LS.get('turnDiffEnabled', '0') === '1'
|
|
4717
|
+
}
|
|
4718
|
+
|
|
4719
|
+
function turnDiffHtmlFor(entry) {
|
|
4720
|
+
if (!turnDiffController || !turnDiffController.isEnabled()) return ''
|
|
4721
|
+
if (entry?.event?.type !== 'turn/end') return ''
|
|
4722
|
+
const turnNumber = Number(entry.event?.data?.turn)
|
|
4723
|
+
if (!Number.isSafeInteger(turnNumber) || turnNumber < 1) return ''
|
|
4724
|
+
const full = turnDiffController.view()
|
|
4725
|
+
const turns = full.turns.filter(turn => turn.turn === turnNumber)
|
|
4726
|
+
if (!turns.length) return ''
|
|
4727
|
+
return `<div class="dr-diff-turn-slot" data-turn="${turnNumber}">${window.DshTurnDiff.viewHtml({ ...full, turns })}</div>`
|
|
4728
|
+
}
|
|
4729
|
+
|
|
4730
|
+
async function fetchHostChangesJson(path, query) {
|
|
4731
|
+
const url = new URL(apiUrl(path), location.href)
|
|
4732
|
+
for (const [key, value] of Object.entries(query || {})) url.searchParams.set(key, String(value))
|
|
4733
|
+
const res = await fetch(url.href, {
|
|
4734
|
+
headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
|
|
4735
|
+
cache: 'no-store',
|
|
4736
|
+
signal: AbortSignal.timeout(45000),
|
|
4737
|
+
})
|
|
4738
|
+
if (res.status === 401) authFailure()
|
|
4739
|
+
let data = null
|
|
4740
|
+
try { data = await res.json() } catch {}
|
|
4741
|
+
return { ok: res.ok, status: res.status, data }
|
|
4742
|
+
}
|
|
4743
|
+
|
|
4744
|
+
let turnDiffActionsBound = false
|
|
4745
|
+
function bindTurnDiffActions() {
|
|
4746
|
+
if (turnDiffActionsBound || !turnDiffController) return
|
|
4747
|
+
const container = $('history')
|
|
4748
|
+
if (!container) return
|
|
4749
|
+
turnDiffActionsBound = true
|
|
4750
|
+
container.addEventListener('click', event => {
|
|
4751
|
+
const button = event.target?.closest?.('[data-dr-diff-action]')
|
|
4752
|
+
if (!button || button.disabled) return
|
|
4753
|
+
const action = button.dataset?.drDiffAction || ''
|
|
4754
|
+
const turn = Number(button.dataset?.drDiffTurn)
|
|
4755
|
+
const index = Number(button.dataset?.drDiffFile)
|
|
4756
|
+
const delivery = Number(button.dataset?.drDiffDelivery)
|
|
4757
|
+
const run = {
|
|
4758
|
+
toggle: () => turnDiffController.toggleTurn(turn),
|
|
4759
|
+
file: () => turnDiffController.selectFile(turn, index),
|
|
4760
|
+
delivery: () => { turnDiffController.openDelivery(turn, delivery); return true },
|
|
4761
|
+
'retry-summary': () => turnDiffController.retrySummary(turn),
|
|
4762
|
+
'retry-diff': () => turnDiffController.retryDiff(turn, index),
|
|
4763
|
+
}[action]
|
|
4764
|
+
if (!run) return
|
|
4765
|
+
const finish = () => { if (state.current) renderHistory(false, 'keep') }
|
|
4766
|
+
try {
|
|
4767
|
+
const result = run()
|
|
4768
|
+
if (result && typeof result.then === 'function') result.then(finish, finish)
|
|
4769
|
+
else finish()
|
|
4770
|
+
} catch { finish() }
|
|
4771
|
+
})
|
|
4772
|
+
}
|
|
4773
|
+
|
|
4774
|
+
function initReviewFeatures() {
|
|
4775
|
+
if (window.DshPlanReview && !planReviewController) {
|
|
4776
|
+
const anchor = $('session-cards')
|
|
4777
|
+
if (anchor) {
|
|
4778
|
+
planReviewHost = document.createElement('section')
|
|
4779
|
+
planReviewHost.id = 'plan-review-host'
|
|
4780
|
+
planReviewHost.className = 'plan-review-host hidden'
|
|
4781
|
+
planReviewHost.setAttribute('aria-live', 'polite')
|
|
4782
|
+
anchor.after(planReviewHost)
|
|
4783
|
+
planReviewController = window.DshPlanReview.create({
|
|
4784
|
+
command: async line => ({ executed: await runSlashCommand(line, true) }),
|
|
4785
|
+
respond: (rpcId, value) => respond(rpcId, value),
|
|
4786
|
+
state: {
|
|
4787
|
+
sessionId: () => state.current,
|
|
4788
|
+
snapshot: sessionId => planReviewSnapshot(sessionId),
|
|
4789
|
+
entries: sessionId => state.current === sessionId ? state.history.visible : [],
|
|
4790
|
+
},
|
|
4791
|
+
dom: { root: planReviewHost },
|
|
4792
|
+
onOpenPlan: () => {},
|
|
4793
|
+
notify: (message, kind) => { if (message) toast(message, kind === 'err' ? 'err' : '') },
|
|
4794
|
+
})
|
|
4795
|
+
updatePlanReviewVisibility(planReviewController.view())
|
|
4796
|
+
}
|
|
4797
|
+
}
|
|
4798
|
+
if (window.DshTurnDiff && !turnDiffController) {
|
|
4799
|
+
turnDiffRoot = document.createElement('div')
|
|
4800
|
+
turnDiffRoot.hidden = true
|
|
4801
|
+
turnDiffController = window.DshTurnDiff.create({
|
|
4802
|
+
state: {
|
|
4803
|
+
sessionId: () => state.current,
|
|
4804
|
+
entries: sessionId => state.current === sessionId ? state.history.visible : [],
|
|
4805
|
+
},
|
|
4806
|
+
fetchJson: fetchHostChangesJson,
|
|
4807
|
+
dom: { root: turnDiffRoot },
|
|
4808
|
+
layout: 'mobile',
|
|
4809
|
+
enabled: turnDiffEnabled,
|
|
4810
|
+
onOpenFile: ({ path }) => {
|
|
4811
|
+
const name = String(path || '').split(/[\\/]/).pop() || ''
|
|
4812
|
+
if (path && name) openFsPreview(path, name)
|
|
4813
|
+
},
|
|
4814
|
+
notify: (message, kind) => { if (message) toast(message, kind === 'err' ? 'err' : '') },
|
|
4815
|
+
})
|
|
4816
|
+
turnDiffController.setEnabled(turnDiffEnabled())
|
|
4817
|
+
bindTurnDiffActions()
|
|
4818
|
+
}
|
|
4819
|
+
initTurnDiffSetting()
|
|
4820
|
+
}
|
|
4821
|
+
|
|
4822
|
+
function initTurnDiffSetting() {
|
|
4823
|
+
const page = $('settings-page-general')
|
|
4824
|
+
if (!page || $('opt-turn-diff')) return
|
|
4825
|
+
// The optional Workflow shell restructures this page after boot; attach to
|
|
4826
|
+
// its stable card when present, else to the static group/page for plain UI.
|
|
4827
|
+
const group = page.querySelector('[data-workflow-settings-slot="input"]')
|
|
4828
|
+
|| page.querySelector('[data-workflow-settings-slot]')
|
|
4829
|
+
|| page.querySelector('.settings-group:last-child')
|
|
4830
|
+
|| page
|
|
4831
|
+
const row = document.createElement('div')
|
|
4832
|
+
row.className = 'setting-row'
|
|
4833
|
+
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>`
|
|
4834
|
+
row.querySelector('.setting-name').textContent = t('settings.turnDiffTitle')
|
|
4835
|
+
row.querySelector('.setting-desc').textContent = t('settings.turnDiffDesc')
|
|
4836
|
+
group.append(row)
|
|
4837
|
+
const checkbox = row.querySelector('#opt-turn-diff')
|
|
4838
|
+
checkbox.checked = turnDiffEnabled()
|
|
4839
|
+
checkbox.addEventListener('change', () => {
|
|
4840
|
+
LS.set('turnDiffEnabled', checkbox.checked ? '1' : '0')
|
|
4841
|
+
turnDiffController?.setEnabled(checkbox.checked)
|
|
4842
|
+
if (state.current) renderHistory(false, 'keep')
|
|
4843
|
+
})
|
|
4844
|
+
}
|
|
4845
|
+
|
|
4846
|
+
function updateTurnDiffSettingLabel() {
|
|
4847
|
+
const row = $('opt-turn-diff')?.closest('.setting-row')
|
|
4848
|
+
if (!row) return
|
|
4849
|
+
const name = row.querySelector('.setting-name')
|
|
4850
|
+
const desc = row.querySelector('.setting-desc')
|
|
4851
|
+
if (name) name.textContent = t('settings.turnDiffTitle')
|
|
4852
|
+
if (desc) desc.textContent = t('settings.turnDiffDesc')
|
|
4853
|
+
}
|
|
4854
|
+
|
|
3934
4855
|
// 主机拥有权限模式(沙箱+审批捆绑)与可选目录;Remote 只按主机返回渲染,
|
|
3935
4856
|
// 不为未安装或不存在的预设造选项。旧主机没有该目录时回退三种沙箱模式。
|
|
3936
4857
|
// 目录直接作为“指令”列表中的权限模式行显示,Auto review 可用时同样出现在这里。
|
|
@@ -3968,6 +4889,7 @@ function toggleComposerMenu() {
|
|
|
3968
4889
|
menu.classList.toggle('hidden', !show)
|
|
3969
4890
|
$('btn-plus').classList.toggle('active', show)
|
|
3970
4891
|
if (show) refreshPermissionPresets()
|
|
4892
|
+
if (show) void window.DshSlashSuggestions?.openPanel()
|
|
3971
4893
|
if (show && !state.models.loaded && !state.models.loading) loadSessionModels()
|
|
3972
4894
|
}
|
|
3973
4895
|
|
|
@@ -4144,11 +5066,16 @@ function loadSessionPresets(prefix) {
|
|
|
4144
5066
|
}
|
|
4145
5067
|
async function newSession(preferredWorkspace = '') {
|
|
4146
5068
|
if (!state.token) { showView('view-settings'); return }
|
|
5069
|
+
const connection = captureConnection()
|
|
5070
|
+
if (await prepareNewSessionForm(preferredWorkspace, connection.valid)) $('modal-new-session').classList.remove('hidden')
|
|
5071
|
+
}
|
|
5072
|
+
async function prepareNewSessionForm(preferredWorkspace, current) {
|
|
4147
5073
|
if (!workspaceItems().length) await refreshWorkbench()
|
|
5074
|
+
if (!current()) return false
|
|
4148
5075
|
const preferred = typeof preferredWorkspace === 'string' && preferredWorkspace || workspaceById(state.workspaceFilter)?.workspaceId || LS.get('lastNewSessionWorkspaceV1', '')
|
|
4149
5076
|
renderNewSessionWorkspace(preferred)
|
|
4150
5077
|
void loadSessionPresets('new-session')
|
|
4151
|
-
|
|
5078
|
+
return true
|
|
4152
5079
|
}
|
|
4153
5080
|
function renderNewSessionWorkspace(preferredId = '') {
|
|
4154
5081
|
const items = workspaceItems()
|
|
@@ -4165,6 +5092,7 @@ function renderNewSessionWorkspace(preferredId = '') {
|
|
|
4165
5092
|
$('new-session-create').disabled = !workspace
|
|
4166
5093
|
}
|
|
4167
5094
|
function closeNewSessionModal() {
|
|
5095
|
+
if (isGroupDrawerPanel('new')) { setGroupDrawerPanel(''); return }
|
|
4168
5096
|
$('modal-new-session').classList.add('hidden')
|
|
4169
5097
|
}
|
|
4170
5098
|
async function createSessionInWorkspace() {
|
|
@@ -4299,21 +5227,10 @@ function repairMissingStreams() {
|
|
|
4299
5227
|
}
|
|
4300
5228
|
}
|
|
4301
5229
|
async function probeOverviewLinks(signal) {
|
|
4302
|
-
const connection=captureConnection()
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
|
|
4306
|
-
timer=setTimeout(cancel,6500)
|
|
4307
|
-
const healthRequest=fetch(base+'/health?probe=fresh&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
|
|
4308
|
-
if(!response.ok)throw Error('health')
|
|
4309
|
-
const health=await response.json();if(health?.ok!==true)throw Error('health')
|
|
4310
|
-
return health
|
|
4311
|
-
}).catch(()=>null).finally(()=>{clearTimeout(timer);signal.removeEventListener('abort',cancel)})
|
|
4312
|
-
const [health,host]=await Promise.all([healthRequest,refreshHostDescription()])
|
|
4313
|
-
if(!connection.valid()||signal.aborted)throw Error('stale check')
|
|
4314
|
-
if(health){state.gatewayHealth[base]=health}
|
|
4315
|
-
else delete state.gatewayHealth[base]
|
|
4316
|
-
return {gateway:!!health}
|
|
5230
|
+
const connection = captureConnection()
|
|
5231
|
+
const [health] = await Promise.all([refreshConnectionHealth(), refreshHostDescription()])
|
|
5232
|
+
if (!connection.valid() || signal.aborted) throw Error('stale check')
|
|
5233
|
+
return { gateway: !!health }
|
|
4317
5234
|
}
|
|
4318
5235
|
function startOverviewDetection(force=false,identityChanged=false) {
|
|
4319
5236
|
if(identityChanged)overviewDetector?.pause()
|
|
@@ -4415,7 +5332,8 @@ function renderOverview() {
|
|
|
4415
5332
|
$('overview-dsh-version').textContent = state.hostInfo?.version || '—'
|
|
4416
5333
|
$('overview-gateway-version').textContent = checks.gateway ? t('overview.online') : t('overview.offlineShort')
|
|
4417
5334
|
$('overview-active-sessions').textContent = String(running)
|
|
4418
|
-
|
|
5335
|
+
const connectionStatus = mobileConnectionStatus()
|
|
5336
|
+
$('overview-connection-mode').textContent = t(connectionStatus === 'conn.on' ? 'overview.ws' : connectionStatus)
|
|
4419
5337
|
$('overview-active-count').textContent = running ? t('overview.activeCount', { n: running }) : ''
|
|
4420
5338
|
$('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)}">
|
|
4421
5339
|
<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>
|
|
@@ -4512,6 +5430,7 @@ function renderPending() {
|
|
|
4512
5430
|
btn.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === btn.dataset.question))))
|
|
4513
5431
|
renderSessionPending()
|
|
4514
5432
|
updatePendingBadge()
|
|
5433
|
+
renderGroupDrawerOperations()
|
|
4515
5434
|
renderOverview()
|
|
4516
5435
|
}
|
|
4517
5436
|
|
|
@@ -4610,6 +5529,11 @@ function fitQuestionViewport() {
|
|
|
4610
5529
|
|
|
4611
5530
|
function openQuestionModal(q) {
|
|
4612
5531
|
if (!q) return
|
|
5532
|
+
if (typeof isPlanReviewQuestion === 'function' && isPlanReviewQuestion(q)) {
|
|
5533
|
+
if (typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
5534
|
+
if (typeof planReviewHost !== 'undefined') planReviewHost?.scrollIntoView?.({ behavior: 'smooth', block: 'center' })
|
|
5535
|
+
return
|
|
5536
|
+
}
|
|
4613
5537
|
state.questionModal = q
|
|
4614
5538
|
$('question-body').innerHTML = q.questions.map((item, i) => `
|
|
4615
5539
|
<div class="q-item">
|
|
@@ -4665,45 +5589,32 @@ async function submitQuestion() {
|
|
|
4665
5589
|
}
|
|
4666
5590
|
|
|
4667
5591
|
/* ---------------- 后台任务 ---------------- */
|
|
4668
|
-
|
|
4669
|
-
|
|
4670
|
-
|
|
4671
|
-
|
|
4672
|
-
|
|
4673
|
-
|
|
4674
|
-
|
|
4675
|
-
|
|
4676
|
-
|
|
4677
|
-
|
|
4678
|
-
|
|
4679
|
-
|
|
4680
|
-
|
|
4681
|
-
|
|
4682
|
-
|
|
4683
|
-
|
|
4684
|
-
|
|
4685
|
-
|
|
4686
|
-
|
|
4687
|
-
|
|
4688
|
-
}
|
|
4689
|
-
}
|
|
5592
|
+
const hostAccess = connection => window.DshHostQueue.readAccess(connection, apiUrl)
|
|
5593
|
+
const hostQueue = window.DshHostQueue?.create({ rpc, access: hostAccess, capture: captureConnection, box: () => $('queue-dock'),
|
|
5594
|
+
session: () => state.current, items: () => state.queues[state.current], running: () => !!state.byId.get(state.current)?.running,
|
|
5595
|
+
apply(sessionId, snapshot) {
|
|
5596
|
+
state.queues[sessionId] = snapshot.items
|
|
5597
|
+
const session = state.byId.get(sessionId)
|
|
5598
|
+
if (session) session.running = snapshot.running
|
|
5599
|
+
},
|
|
5600
|
+
})
|
|
5601
|
+
const hostSchedule = window.DshHostSchedule?.create({ rpc, access: hostAccess, capture: captureConnection, box: () => $('view-schedule'),
|
|
5602
|
+
workspaces: workspaceItems,
|
|
5603
|
+
sessions: () => state.sessions.filter(row => row.origin !== 'subagent' && !(state.wbArchived || []).includes(row.sessionId)).map(row => ({ id: row.sessionId, label: titleOf(row) })),
|
|
5604
|
+
async openSession(id) {
|
|
5605
|
+
const connection = captureConnection()
|
|
5606
|
+
await refreshSessions()
|
|
5607
|
+
if (!connection.valid()) return
|
|
5608
|
+
if (!state.byId.has(id)) return toast(t('session.unknown'), 'err')
|
|
5609
|
+
await openSession(id)
|
|
5610
|
+
},
|
|
5611
|
+
})
|
|
4690
5612
|
function renderQueue() {
|
|
4691
5613
|
renderComposerSend()
|
|
5614
|
+
hostQueue?.render()
|
|
4692
5615
|
const s = state.byId.get(state.current)
|
|
4693
5616
|
if (!s) return
|
|
4694
5617
|
const items = (state.queues[state.current] || []).filter(item => item?.placement === 'queued')
|
|
4695
|
-
const box = $('queue-dock')
|
|
4696
|
-
if (box) {
|
|
4697
|
-
box.classList.toggle('hidden', !items.length)
|
|
4698
|
-
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 => {
|
|
4699
|
-
const key = `${state.current}:${item.id}`
|
|
4700
|
-
const busy = !!state.queueSteering[key]
|
|
4701
|
-
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>`
|
|
4702
|
-
}).join('')}</div>` : ''
|
|
4703
|
-
box.querySelectorAll('[data-queue-steer]').forEach(button => {
|
|
4704
|
-
button.addEventListener('click', () => steerQueueItem(button.dataset.queueSteer))
|
|
4705
|
-
})
|
|
4706
|
-
}
|
|
4707
5618
|
updateCancelBtn()
|
|
4708
5619
|
updateSessionStatus()
|
|
4709
5620
|
// 队列数量在会话列表已显示; 详情页不重复大 UI
|
|
@@ -4932,6 +5843,11 @@ async function chatImageAttachment(attachment, sessionId) {
|
|
|
4932
5843
|
...(ref.height === undefined ? {} : { height: ref.height }),
|
|
4933
5844
|
...(ref.name ? { name: ref.name } : {}),
|
|
4934
5845
|
} }
|
|
5846
|
+
const session = state.byId?.get(sessionId)
|
|
5847
|
+
if (session?.origin === 'subagent' && session.parentSessionId) {
|
|
5848
|
+
payload.parentSessionId = session.parentSessionId
|
|
5849
|
+
payload.subagentMode = session.subagentMode || 'unknown'
|
|
5850
|
+
}
|
|
4935
5851
|
const result = await rpc('session.attachment', payload, 120000)
|
|
4936
5852
|
if (!connection.valid() || state.current !== sessionId) throw new Error('stale image')
|
|
4937
5853
|
return result
|
|
@@ -5609,14 +6525,20 @@ async function maybeWarnAppBehindGateway({ probe = false } = {}) {
|
|
|
5609
6525
|
function closeAppVersionWarning(checkNow = false) {
|
|
5610
6526
|
$('modal-app-version-warning').classList.add('hidden')
|
|
5611
6527
|
if (checkNow) {
|
|
5612
|
-
|
|
5613
|
-
showSettingsPage('about')
|
|
5614
|
-
void checkUpdate(false)
|
|
6528
|
+
openUpdateSettings()
|
|
5615
6529
|
} else {
|
|
5616
6530
|
scheduleStartupNotices(150)
|
|
5617
6531
|
}
|
|
5618
6532
|
}
|
|
5619
6533
|
|
|
6534
|
+
function openUpdateSettings() {
|
|
6535
|
+
showView('view-settings')
|
|
6536
|
+
showSettingsPage('about')
|
|
6537
|
+
$('settings-update-row')?.scrollIntoView({ block: 'start' })
|
|
6538
|
+
$('btn-check-update')?.focus({ preventScroll: true })
|
|
6539
|
+
void checkUpdate(false)
|
|
6540
|
+
}
|
|
6541
|
+
|
|
5620
6542
|
function resetUpdateExpand() {
|
|
5621
6543
|
const desc = $('update-desc')
|
|
5622
6544
|
if (desc) desc.classList.remove('expanded')
|
|
@@ -5640,6 +6562,11 @@ async function loadLocalVersion() {
|
|
|
5640
6562
|
const res = await fetch('version.json?t=' + Date.now())
|
|
5641
6563
|
if (res.ok) state.localVersion = (await res.json())?.version || ''
|
|
5642
6564
|
} catch {}
|
|
6565
|
+
if (!state.localVersion && CAP?.isNativePlatform?.()) {
|
|
6566
|
+
state.localVersion = (window.NativeUpdate?.getInstalledVersion?.() || '').replace(/\.rc\.(\d+)$/, '-rc.$1')
|
|
6567
|
+
}
|
|
6568
|
+
const drawerVersion = $('group-drawer-version')
|
|
6569
|
+
if (drawerVersion) drawerVersion.textContent = state.localVersion ? 'v' + state.localVersion : '—'
|
|
5643
6570
|
$('update-desc').textContent = state.localVersion ? t('update.currentV', { version: state.localVersion }) : t('update.noVersion')
|
|
5644
6571
|
}
|
|
5645
6572
|
|
|
@@ -6196,7 +7123,10 @@ function closeNotesModal() {
|
|
|
6196
7123
|
if (notesVersion) { LS.set(NOTES_KEY, notesVersion); notesVersion = '' }
|
|
6197
7124
|
}
|
|
6198
7125
|
|
|
7126
|
+
let activeUpdateCheck
|
|
7127
|
+
|
|
6199
7128
|
async function checkUpdate(silent) {
|
|
7129
|
+
if (silent && activeUpdateCheck && !activeUpdateCheck.silent) return
|
|
6200
7130
|
if (!state.localVersion) {
|
|
6201
7131
|
$('update-desc').textContent = t('update.noVersion')
|
|
6202
7132
|
resetUpdateExpand()
|
|
@@ -6204,27 +7134,54 @@ async function checkUpdate(silent) {
|
|
|
6204
7134
|
return
|
|
6205
7135
|
}
|
|
6206
7136
|
const base = updateBase()
|
|
6207
|
-
|
|
7137
|
+
const connection = captureConnection()
|
|
7138
|
+
const native = window.NativeUpdate
|
|
7139
|
+
const canCheckOfficial = !silent && CAP?.isNativePlatform?.() && native?.checkOfficialRelease
|
|
7140
|
+
&& native.getOfficialReleaseStatus && native.downloadOfficialRelease && native.getDownloadStatus
|
|
7141
|
+
if (!base && !canCheckOfficial) {
|
|
6208
7142
|
if (!silent) toast(t('update.needServer'), 'err')
|
|
6209
7143
|
$('update-desc').textContent = state.localVersion ? `${t('update.currentV', { version: state.localVersion })} · ${t('update.needServer')}` : t('update.needServer')
|
|
6210
7144
|
resetUpdateExpand()
|
|
6211
7145
|
return
|
|
6212
7146
|
}
|
|
7147
|
+
const request = { silent }
|
|
7148
|
+
activeUpdateCheck = request
|
|
7149
|
+
const valid = () => activeUpdateCheck === request && connection.valid()
|
|
6213
7150
|
if (!silent) toast(t('update.checking'))
|
|
6214
7151
|
try {
|
|
6215
|
-
|
|
6216
|
-
if (
|
|
6217
|
-
|
|
7152
|
+
let info
|
|
7153
|
+
if (base) {
|
|
7154
|
+
try {
|
|
7155
|
+
const res = await fetch(base + '/update.json?t=' + Date.now() + '&local=' + encodeURIComponent(state.localVersion),
|
|
7156
|
+
{ signal: AbortSignal.timeout(8000), cache: 'no-store' })
|
|
7157
|
+
if (!res.ok) throw new Error('HTTP ' + res.status)
|
|
7158
|
+
const host = await res.json()
|
|
7159
|
+
if (typeof host?.version !== 'string' || !host.version) throw new Error(t('update.noVersion'))
|
|
7160
|
+
if (canCheckOfficial && cmpVersion(host.version, state.localVersion) > 0 && !/^[a-f0-9]{64}$/i.test(host.sha256 || '')) {
|
|
7161
|
+
throw new Error(t('update.hashMissing'))
|
|
7162
|
+
}
|
|
7163
|
+
info = { ...host, source: 'host', base }
|
|
7164
|
+
} catch (error) {
|
|
7165
|
+
if (!canCheckOfficial) throw error
|
|
7166
|
+
}
|
|
7167
|
+
}
|
|
7168
|
+
if (!valid()) return
|
|
7169
|
+
if (canCheckOfficial && (!info || cmpVersion(info.version, state.localVersion) <= 0)) {
|
|
7170
|
+
info = await checkOfficialAndroidRelease(native, valid)
|
|
7171
|
+
if (!valid()) return
|
|
7172
|
+
}
|
|
6218
7173
|
if (!silent || !window.DshWorkflow?.isMounted()) openNotesModal(info)
|
|
6219
7174
|
if (info.version && cmpVersion(info.version, state.localVersion) > 0) {
|
|
6220
7175
|
state.updateInfo = info
|
|
6221
7176
|
const hasNotes = !!(info.notes && String(info.notes).trim())
|
|
6222
|
-
$('update-desc').textContent =
|
|
7177
|
+
$('update-desc').textContent = info.source === 'official'
|
|
7178
|
+
? t('update.foundOfficial', { version: info.version })
|
|
7179
|
+
: t('update.found', { version: info.version, notes: hasNotes ? ':' + info.notes : '' })
|
|
6223
7180
|
$('update-desc').classList.remove('expanded')
|
|
6224
7181
|
$('btn-update-expand').classList.toggle('hidden', !hasNotes)
|
|
6225
7182
|
renderUpdateExpandBtn()
|
|
6226
7183
|
$('btn-download-update').classList.remove('hidden')
|
|
6227
|
-
if (!silent) toast(t('update.found', { version: info.version }), 'ok')
|
|
7184
|
+
if (!silent) toast(t(info.source === 'official' ? 'update.foundOfficial' : 'update.found', { version: info.version }), 'ok')
|
|
6228
7185
|
else notify(t('update.foundTitle'), t('update.foundBody', { version: info.version }))
|
|
6229
7186
|
} else {
|
|
6230
7187
|
state.updateInfo = null
|
|
@@ -6234,9 +7191,16 @@ async function checkUpdate(silent) {
|
|
|
6234
7191
|
if (!silent) toast(t('update.latestToast'), 'ok')
|
|
6235
7192
|
}
|
|
6236
7193
|
} catch (e) {
|
|
7194
|
+
if (!valid()) return
|
|
7195
|
+
if (!silent) {
|
|
7196
|
+
state.updateInfo = null
|
|
7197
|
+
$('btn-download-update').classList.add('hidden')
|
|
7198
|
+
}
|
|
6237
7199
|
$('update-desc').textContent = t('update.checkFailedDesc', { msg: e.message || t('fs.networkError') })
|
|
6238
7200
|
resetUpdateExpand()
|
|
6239
7201
|
if (!silent) toast(t('update.checkFailed', { msg: e.message }), 'err')
|
|
7202
|
+
} finally {
|
|
7203
|
+
if (activeUpdateCheck === request) activeUpdateCheck = null
|
|
6240
7204
|
}
|
|
6241
7205
|
}
|
|
6242
7206
|
|
|
@@ -6249,6 +7213,21 @@ let updateDownloadBusy = false
|
|
|
6249
7213
|
let updateDownloadTimer = null
|
|
6250
7214
|
let updateDownloadSample = null
|
|
6251
7215
|
|
|
7216
|
+
async function checkOfficialAndroidRelease(native, valid) {
|
|
7217
|
+
$('update-desc').textContent = t('update.checkingOfficial')
|
|
7218
|
+
native.checkOfficialRelease()
|
|
7219
|
+
const deadline = Date.now() + 24000
|
|
7220
|
+
while (valid() && Date.now() < deadline) {
|
|
7221
|
+
const status = JSON.parse(native.getOfficialReleaseStatus())
|
|
7222
|
+
if (status.phase === 'complete' && /^\d+\.\d+\.\d+$/.test(status.version) && /^[a-f0-9]{64}$/i.test(status.sha256)) {
|
|
7223
|
+
return { source: 'official', version: status.version, sha256: status.sha256 }
|
|
7224
|
+
}
|
|
7225
|
+
if (status.phase !== 'checking') break
|
|
7226
|
+
await new Promise(resolve => setTimeout(resolve, 250))
|
|
7227
|
+
}
|
|
7228
|
+
throw new Error(t('update.officialUnavailable'))
|
|
7229
|
+
}
|
|
7230
|
+
|
|
6252
7231
|
function updateDownloadProgress(value) {
|
|
6253
7232
|
const box = $('update-download-progress')
|
|
6254
7233
|
if (!box) return
|
|
@@ -6264,8 +7243,14 @@ function updateDownloadProgress(value) {
|
|
|
6264
7243
|
if (total > 0) bar.value = Math.min(100, received * 100 / total)
|
|
6265
7244
|
else bar.removeAttribute('value')
|
|
6266
7245
|
const phase = value.phase || 'downloading'
|
|
6267
|
-
|
|
6268
|
-
|
|
7246
|
+
let status
|
|
7247
|
+
if (phase !== 'error') status = t(`update.phase.${phase}`)
|
|
7248
|
+
else if (value.code === 'installer') status = t('update.installerFailed')
|
|
7249
|
+
else if (value.code === 'verify') status = t(value.patch ? 'update.patchMismatch' : 'update.corrupted')
|
|
7250
|
+
else if (value.code === 'storage') status = t('update.storageFailed')
|
|
7251
|
+
else status = t('update.downloadFailed', { msg: value.error || t('fs.networkError') })
|
|
7252
|
+
$('update-download-status').textContent = status
|
|
7253
|
+
$('update-download-detail').textContent = `${total > 0 ? `${Math.min(100, received * 100 / total).toFixed(0)}% · ` : ''}${format(received)}${total > 0 ? ` / ${format(total)}` : ''} · ${format(phase === 'downloading' || phase === 'official' ? updateDownloadSample.speed : 0)}/s`
|
|
6269
7254
|
}
|
|
6270
7255
|
|
|
6271
7256
|
function finishUpdateDownload() {
|
|
@@ -6317,9 +7302,10 @@ async function verifyUpdateApk(info, url) {
|
|
|
6317
7302
|
|
|
6318
7303
|
async function downloadUpdate(force = false) {
|
|
6319
7304
|
if (updateDownloadBusy || (force !== true && !state.updateInfo)) return
|
|
6320
|
-
const base=updateBase()
|
|
6321
|
-
|
|
6322
|
-
|
|
7305
|
+
const base = updateBase()
|
|
7306
|
+
const official = !force && state.updateInfo?.source === 'official'
|
|
7307
|
+
if (!official && !base) { toast(t('update.needServer'), 'err'); return }
|
|
7308
|
+
const connection = captureConnection()
|
|
6323
7309
|
updateDownloadBusy = true
|
|
6324
7310
|
updateDownloadSample = null
|
|
6325
7311
|
$('btn-download-update').disabled = true
|
|
@@ -6338,24 +7324,39 @@ async function downloadUpdate(force = false) {
|
|
|
6338
7324
|
if(!connection.valid())return
|
|
6339
7325
|
const sha256=String(info?.sha256||'').trim().toLowerCase()
|
|
6340
7326
|
if(!/^[0-9a-f]{64}$/.test(sha256))throw new Error(t('update.hashMissing'))
|
|
6341
|
-
|
|
6342
|
-
|
|
6343
|
-
|
|
6344
|
-
|
|
6345
|
-
|
|
6346
|
-
|
|
7327
|
+
if (!official && info.base && info.base !== base) throw new Error(t('update.checkAgain'))
|
|
7328
|
+
const target = official ? null : new URL(info.apkUrl || 'dsh-remote.apk', base + '/')
|
|
7329
|
+
if (force) target.searchParams.set('dshPatch', Date.now().toString(36) + '-' + sha256.slice(0, 16))
|
|
7330
|
+
const url = target?.href
|
|
7331
|
+
updateDownloadProgress({ phase: official ? 'official' : 'downloading' })
|
|
7332
|
+
const native = window.NativeUpdate
|
|
7333
|
+
if (CAP?.isNativePlatform?.() && native?.downloadVerifiedAndInstall && native.getDownloadStatus) {
|
|
7334
|
+
const started = official ? native.downloadOfficialRelease(info.version, sha256) : native.downloadVerifiedAndInstall(url, sha256)
|
|
7335
|
+
if (!started) throw new Error(t('update.busy'))
|
|
7336
|
+
let usingOfficial = official
|
|
6347
7337
|
nativePending=true
|
|
6348
7338
|
const poll = () => {
|
|
6349
7339
|
try {
|
|
6350
|
-
const value = JSON.parse(
|
|
6351
|
-
|
|
6352
|
-
|
|
7340
|
+
const value = JSON.parse(native.getDownloadStatus())
|
|
7341
|
+
if (value.phase === 'error' && value.code === 'unavailable' && !force && !usingOfficial
|
|
7342
|
+
&& connection.valid() && /^\d+\.\d+\.\d+$/.test(info.version) && native.downloadOfficialRelease) {
|
|
7343
|
+
// The host and GitHub may serve different builds with the same version.
|
|
7344
|
+
if (native.downloadOfficialRelease(info.version, sha256)) {
|
|
7345
|
+
usingOfficial = true
|
|
7346
|
+
updateDownloadProgress({ phase: 'official' })
|
|
7347
|
+
return
|
|
7348
|
+
}
|
|
7349
|
+
}
|
|
7350
|
+
if (usingOfficial && value.phase === 'downloading') value.phase = 'official'
|
|
7351
|
+
updateDownloadProgress({ ...value, patch: force })
|
|
7352
|
+
if (['complete', 'installer', 'error'].includes(value.phase)) finishUpdateDownload()
|
|
6353
7353
|
} catch (error) { updateDownloadProgress({ phase: 'error', error: error.message }); finishUpdateDownload() }
|
|
6354
7354
|
}
|
|
6355
7355
|
updateDownloadTimer = setInterval(poll, 500)
|
|
6356
7356
|
poll()
|
|
6357
7357
|
return
|
|
6358
7358
|
}
|
|
7359
|
+
if (official) throw new Error(t('update.officialUnavailable'))
|
|
6359
7360
|
const result = await verifyUpdateApk(info, url)
|
|
6360
7361
|
if(!connection.valid())return
|
|
6361
7362
|
if (!result.ok) throw new Error(result.corrupted ? t(force===true?'update.patchMismatch':'update.corrupted') : result.status ? t('update.serverFileMissing') : result.msg || t('fs.networkError'))
|
|
@@ -7246,6 +8247,8 @@ async function openModelConfigDocument() {
|
|
|
7246
8247
|
}
|
|
7247
8248
|
/* ---------------- 视图切换 ---------------- */
|
|
7248
8249
|
function showView(id, pluginRoute = 'manage') {
|
|
8250
|
+
if (groupDrawerOpen()) closeGroupDrawer({ restoreFocus: false })
|
|
8251
|
+
window.DshSlashSuggestions?.close()
|
|
7249
8252
|
window.DshExtensions?.closeShortcuts()
|
|
7250
8253
|
if (id !== 'view-session') window.DshSubagents?.close()
|
|
7251
8254
|
document.body?.classList.toggle('viewing-subagent', id === 'view-session' && state.byId.get(state.current)?.origin === 'subagent')
|
|
@@ -7253,7 +8256,10 @@ function showView(id, pluginRoute = 'manage') {
|
|
|
7253
8256
|
if (window.DshWorkflow?.isMounted() && id === 'view-activity') id = 'view-home'
|
|
7254
8257
|
if (id !== 'view-session') conversationView?.pause()
|
|
7255
8258
|
if (id !== 'view-session' && document.body.classList.contains('in-session') && state.current) void archiveEmptySessionOnLeave(state.current)
|
|
7256
|
-
|
|
8259
|
+
const leavingSchedule = id !== 'view-schedule' && !$('view-schedule').classList.contains('hidden')
|
|
8260
|
+
for (const v of ['view-home', 'view-files', 'view-session', 'view-activity', 'view-plugins', 'view-settings', 'view-schedule']) $(v).classList.toggle('hidden', v !== id)
|
|
8261
|
+
if (leavingSchedule) hostSchedule?.leave()
|
|
8262
|
+
if (id === 'view-schedule') void hostSchedule?.refresh(true)
|
|
7257
8263
|
// 离开会话页必须清掉 in-session, 否则其他页面顶栏被 body 样式隐藏
|
|
7258
8264
|
document.body.classList.toggle('in-session', id === 'view-session')
|
|
7259
8265
|
window.DshFileInbox?.render()
|
|
@@ -7261,7 +8267,8 @@ function showView(id, pluginRoute = 'manage') {
|
|
|
7261
8267
|
if (id === 'view-session') conversationView?.resume()
|
|
7262
8268
|
$('session-actions')?.close()
|
|
7263
8269
|
$('session-info')?.close()
|
|
7264
|
-
|
|
8270
|
+
const navView = id === 'view-schedule' ? 'view-settings' : id
|
|
8271
|
+
document.querySelectorAll('.nav-btn').forEach(b => b.classList.toggle('active', b.dataset.view === navView))
|
|
7265
8272
|
window.DshMotion?.view($(id))
|
|
7266
8273
|
window.scrollTo(0, 0)
|
|
7267
8274
|
if (id === 'view-files' && !state.fs.loaded) {
|
|
@@ -7274,7 +8281,7 @@ function showView(id, pluginRoute = 'manage') {
|
|
|
7274
8281
|
if(id==='view-activity')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}
|
|
7275
8282
|
}
|
|
7276
8283
|
|
|
7277
|
-
const SETTINGS_GROUPS = ['general', 'model', 'tests', 'servers', 'notify', 'theme', 'about']
|
|
8284
|
+
const SETTINGS_GROUPS = ['general', 'model', 'tests', 'servers', 'cloud-relay', 'notify', 'theme', 'about']
|
|
7278
8285
|
function showSettingsHome() {
|
|
7279
8286
|
const home = $('settings-home')
|
|
7280
8287
|
if (!home) return
|
|
@@ -7287,8 +8294,30 @@ function showSettingsPage(name) {
|
|
|
7287
8294
|
if (!home || !SETTINGS_GROUPS.includes(name)) return
|
|
7288
8295
|
home.classList.add('hidden')
|
|
7289
8296
|
for (const g of SETTINGS_GROUPS) $('settings-page-' + g)?.classList.toggle('hidden', g !== name)
|
|
8297
|
+
if (name === 'servers') {
|
|
8298
|
+
const openSections = $('settings-page-servers')?.querySelectorAll('.workflow-settings-disclosure[open]')
|
|
8299
|
+
openSections?.forEach(section => { section.open = false })
|
|
8300
|
+
}
|
|
7290
8301
|
window.scrollTo(0, 0)
|
|
7291
8302
|
if (name === 'model') void loadModelSettings()
|
|
8303
|
+
if (name === 'general' && typeof initTurnDiffSetting === 'function') initTurnDiffSetting()
|
|
8304
|
+
}
|
|
8305
|
+
|
|
8306
|
+
function mobileConnectionStatus() {
|
|
8307
|
+
const issue = activeConnectionIssue()
|
|
8308
|
+
if (issue) return issue === 426 ? 'conn.pairingRequired' : 'conn.authFailed'
|
|
8309
|
+
if (!navigator.onLine) return 'conn.offline'
|
|
8310
|
+
if (!state.token) return 'conn.off'
|
|
8311
|
+
const health = currentConnectionHealth()
|
|
8312
|
+
if (health === undefined) return 'conn.checking'
|
|
8313
|
+
if (health === null) return 'conn.gatewayOffline'
|
|
8314
|
+
const upstream = health.upstreamOk ?? health.upstreamReachable
|
|
8315
|
+
if (upstream === false) return 'conn.dshOffline'
|
|
8316
|
+
if (upstream !== true && (!state.hostInfo || state.hostInfo.metadataOnly === true)) return 'conn.checking'
|
|
8317
|
+
if (state.streamMode === 'poll' && state.pollSeq.muxReady) return 'conn.poll'
|
|
8318
|
+
if (state.streamMode === 'ws' && state.streamsOk?.mux && health.events?.mux?.connected !== false) return 'conn.on'
|
|
8319
|
+
if (reconnectInfo) return 'conn.reconnecting'
|
|
8320
|
+
return state.errCount > 0 ? 'conn.failed' : 'conn.checking'
|
|
7292
8321
|
}
|
|
7293
8322
|
|
|
7294
8323
|
function updateConn() {
|
|
@@ -7301,36 +8330,17 @@ function updateConn() {
|
|
|
7301
8330
|
const ms = cur ? state.serverLatency[serverKey(cur)] : undefined
|
|
7302
8331
|
const curGroup = cur ? cur.group : state.activeGroup
|
|
7303
8332
|
const curLabel = cur ? (cur.note || cur.url) : (state.server || t('speed.origin'))
|
|
7304
|
-
const
|
|
7305
|
-
|
|
7306
|
-
|
|
7307
|
-
|
|
7308
|
-
|
|
7309
|
-
|
|
7310
|
-
|
|
7311
|
-
|
|
7312
|
-
|
|
7313
|
-
|
|
7314
|
-
|
|
7315
|
-
return
|
|
7316
|
-
}
|
|
7317
|
-
const ok = !!state.streamsOk?.mux
|
|
7318
|
-
if (!ok && reconnectInfo) {
|
|
7319
|
-
const remain = Math.max(0, Math.ceil((reconnectInfo.at - Date.now()) / 1000))
|
|
7320
|
-
el.textContent = remain > 0 ? t('conn.reconnectIn', { n: remain }) : t('conn.reconnecting')
|
|
7321
|
-
el.className = 'topbar-btn conn-badge off'
|
|
7322
|
-
el.title = t('conn.reconnecting') + ' · ' + titleBase
|
|
7323
|
-
return
|
|
7324
|
-
}
|
|
7325
|
-
if (!ok && state.errCount > 0) {
|
|
7326
|
-
el.textContent = t('conn.failed')
|
|
7327
|
-
el.className = 'topbar-btn conn-badge off'
|
|
7328
|
-
el.title = titleBase
|
|
7329
|
-
return
|
|
7330
|
-
}
|
|
7331
|
-
el.textContent = ok ? t('conn.on') : t('conn.off')
|
|
7332
|
-
el.className = 'topbar-btn conn-badge ' + (ok ? 'on' : 'off')
|
|
7333
|
-
el.title = titleBase
|
|
8333
|
+
const actionTitle = window.DshWorkflow?.isMounted() ? 'conn.details' : 'conn.refresh'
|
|
8334
|
+
const titleBase = t('conn.titleGroup', { group: curGroup, url: curLabel, ms: Number.isFinite(ms) ? ms + 'ms' : '—' }) + ' · ' + t(actionTitle)
|
|
8335
|
+
const issue = activeConnectionIssue()
|
|
8336
|
+
const hint = $(el.getAttribute('aria-describedby'))
|
|
8337
|
+
if (hint) hint.textContent = t(issue ? 'conn.troubleshoot' : hint.dataset.i18n)
|
|
8338
|
+
const status = mobileConnectionStatus()
|
|
8339
|
+
const remain = status === 'conn.reconnecting' ? Math.ceil((reconnectInfo.at - Date.now()) / 1000) : 0
|
|
8340
|
+
el.textContent = remain > 0 ? t('conn.reconnectIn', { n: remain }) : t(status)
|
|
8341
|
+
el.className = 'topbar-btn conn-badge ' + (status === 'conn.on' ? 'on' : 'off')
|
|
8342
|
+
const statusTitle = issue ? t('conn.troubleshoot') : status === 'conn.poll' ? t('conn.pollTitle') : ''
|
|
8343
|
+
el.title = statusTitle ? statusTitle + ' · ' + titleBase : titleBase
|
|
7334
8344
|
}
|
|
7335
8345
|
|
|
7336
8346
|
function autosize(el) {
|
|
@@ -7457,7 +8467,7 @@ function applyPairUrl(url, options = {}) {
|
|
|
7457
8467
|
if (/^[a-f0-9]{32}$/.test(setupId || '') && window.NativeE2ee?.configure) {
|
|
7458
8468
|
relaySetup = { id: setupId, token: tok, servers }
|
|
7459
8469
|
showView('view-settings')
|
|
7460
|
-
showSettingsPage('
|
|
8470
|
+
showSettingsPage('cloud-relay')
|
|
7461
8471
|
requestAnimationFrame(() => {
|
|
7462
8472
|
$('relay-phone-pairing')?.scrollIntoView({ block: 'start' })
|
|
7463
8473
|
const connection = captureConnection()
|
|
@@ -8028,7 +9038,9 @@ const THEME_META = [
|
|
|
8028
9038
|
{ id: 'bocchi', sw: ['#FFD9E8', '#FFFFFF', '#D0105A'] },
|
|
8029
9039
|
{ id: 'nijika', sw: ['#FFF3D5', '#FFFFFF', '#94600C'] },
|
|
8030
9040
|
{ id: 'ryo', sw: ['#E9F1FA', '#FFFFFF', '#315D91'] },
|
|
8031
|
-
{ id: 'kita', sw: ['#FFE9E5', '#FFFFFF', '#B6373C'] }
|
|
9041
|
+
{ id: 'kita', sw: ['#FFE9E5', '#FFFFFF', '#B6373C'] },
|
|
9042
|
+
{ id: 'penguin-logistics', sw: ['#12161B', '#1D252E', '#E9B66F'] },
|
|
9043
|
+
{ id: 'miku', sw: ['#F3FFFC', '#FFFFFF', '#126D69'] }
|
|
8032
9044
|
]
|
|
8033
9045
|
|
|
8034
9046
|
function renderThemeBtn() {
|
|
@@ -8061,7 +9073,7 @@ function bindSessionDialogs() {
|
|
|
8061
9073
|
observer.observe($('session-sub'))
|
|
8062
9074
|
}
|
|
8063
9075
|
const actions=$('session-actions'), info=$('session-info');
|
|
8064
|
-
$('btn-session-more').addEventListener('click',()=>actions.showModal());
|
|
9076
|
+
$('btn-session-more').addEventListener('click',()=>{if(typeof refreshSessionAdminActions === 'function')refreshSessionAdminActions();actions.showModal()});
|
|
8065
9077
|
actions.addEventListener('click',e=>{if(e.target===actions)actions.close();else if(e.target.closest('button'))actions.close()},true);
|
|
8066
9078
|
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()};
|
|
8067
9079
|
$('session-title').addEventListener('click',openInfo);
|
|
@@ -8090,6 +9102,9 @@ function bindUi() {
|
|
|
8090
9102
|
if (state.current) { renderSessionTitle(); renderSessionSub(); renderSessionCards(); renderHistory(true) }
|
|
8091
9103
|
else renderModelMenu()
|
|
8092
9104
|
loadLocalVersion()
|
|
9105
|
+
if (typeof updateBcControlLabels === 'function') updateBcControlLabels()
|
|
9106
|
+
if (typeof updateTurnDiffSettingLabel === 'function') updateTurnDiffSettingLabel()
|
|
9107
|
+
if (state.current && typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
8093
9108
|
if (state.hostInfo) $('host-desc').textContent = hostDescriptionText(state.hostInfo)
|
|
8094
9109
|
$('token-desc').textContent = state.token ? t('token.savedLocal') : t('token.notSet')
|
|
8095
9110
|
})
|
|
@@ -8108,6 +9123,7 @@ function bindUi() {
|
|
|
8108
9123
|
// 底部导航
|
|
8109
9124
|
document.querySelectorAll('.nav-btn').forEach(b =>
|
|
8110
9125
|
b.addEventListener('click', () => showView(b.dataset.view)))
|
|
9126
|
+
$('btn-host-schedule')?.addEventListener('click', () => showView('view-schedule'))
|
|
8111
9127
|
$('overview-primary-action').addEventListener('click', () => {
|
|
8112
9128
|
const button = $('overview-primary-action')
|
|
8113
9129
|
const action = button.dataset.overviewAction
|
|
@@ -8139,6 +9155,12 @@ function bindUi() {
|
|
|
8139
9155
|
archiveSession(archive.dataset.archiveSession)
|
|
8140
9156
|
return
|
|
8141
9157
|
}
|
|
9158
|
+
const unarchive = e.target.closest('[data-unarchive-session]')
|
|
9159
|
+
if (unarchive) {
|
|
9160
|
+
e.stopPropagation()
|
|
9161
|
+
if (typeof unarchiveSessionFromList === 'function') void unarchiveSessionFromList(unarchive.dataset.unarchiveSession)
|
|
9162
|
+
return
|
|
9163
|
+
}
|
|
8142
9164
|
const swipeRow = e.target.closest('[data-session-swipe]')
|
|
8143
9165
|
if (swipeRow?.classList.contains('revealed')) {
|
|
8144
9166
|
swipeRow.classList.remove('revealed')
|
|
@@ -8180,7 +9202,12 @@ function bindUi() {
|
|
|
8180
9202
|
$('btn-insights').addEventListener('click', () => openInsights())
|
|
8181
9203
|
$('context-ring')?.addEventListener('click', () => { if (contextUsage()) void openInsights('context', true) })
|
|
8182
9204
|
$('stats-close').addEventListener('click', () => $('modal-stats').classList.add('hidden'))
|
|
8183
|
-
$('conn-badge').addEventListener('click', () => {
|
|
9205
|
+
$('conn-badge').addEventListener('click', () => {
|
|
9206
|
+
if (window.DshWorkflow?.isMounted()) return window.DshWorkflow.connectionDetails()
|
|
9207
|
+
toast(t('common.refreshing'))
|
|
9208
|
+
openStreams()
|
|
9209
|
+
void refreshAll()
|
|
9210
|
+
})
|
|
8184
9211
|
window.DshExtensions?.bindShortcuts({ trigger: $('btn-plugin-shortcuts'), menu: $('plugin-shortcuts-menu'),
|
|
8185
9212
|
config: () => optionalPluginConfig(), connected: () => !!state.token, hasSession: () => !!state.current,
|
|
8186
9213
|
beforeOpen: () => { closeGroupDrawer({ restoreFocus: false }) },
|
|
@@ -8212,6 +9239,17 @@ function bindUi() {
|
|
|
8212
9239
|
else if (e.key === 'Escape' && isAppVersionWarningOpen()) closeAppVersionWarning(false)
|
|
8213
9240
|
})
|
|
8214
9241
|
$('btn-new-session').addEventListener('click', newSession)
|
|
9242
|
+
const workspaceActions = $('session-workspace-actions')
|
|
9243
|
+
document.addEventListener('click', event => {
|
|
9244
|
+
if (workspaceActions.open && (!workspaceActions.contains(event.target) || event.target.closest('button'))) {
|
|
9245
|
+
workspaceActions.open = false
|
|
9246
|
+
}
|
|
9247
|
+
})
|
|
9248
|
+
workspaceActions.addEventListener('keydown', event => {
|
|
9249
|
+
if (event.key !== 'Escape' || !workspaceActions.open) return
|
|
9250
|
+
workspaceActions.open = false
|
|
9251
|
+
workspaceActions.querySelector('summary').focus()
|
|
9252
|
+
})
|
|
8215
9253
|
$('session-workspace-filter').addEventListener('change', (e) => {
|
|
8216
9254
|
state.workspaceFilter = e.target.value
|
|
8217
9255
|
if (state.workspaceFilter) LS.set('workspaceFilterV1', state.workspaceFilter)
|
|
@@ -8295,10 +9333,14 @@ function bindUi() {
|
|
|
8295
9333
|
$('composer-menu').addEventListener('click', async (e) => {
|
|
8296
9334
|
const chip = e.target.closest('[data-cmd]')
|
|
8297
9335
|
if (chip) {
|
|
8298
|
-
const
|
|
8299
|
-
|
|
8300
|
-
|
|
8301
|
-
|
|
9336
|
+
const command = String(chip.dataset.cmd || '').replace(/^\/+/, '')
|
|
9337
|
+
if (typeof composerTools === 'undefined' || !composerTools?.insertCommand?.(command)) {
|
|
9338
|
+
const input = $('composer-input')
|
|
9339
|
+
if (input.value.trim()) input.value = '/' + command + ' ' + input.value
|
|
9340
|
+
else input.value = '/' + command + ' '
|
|
9341
|
+
input.focus()
|
|
9342
|
+
autosize(input)
|
|
9343
|
+
}
|
|
8302
9344
|
hideComposerMenu()
|
|
8303
9345
|
return
|
|
8304
9346
|
}
|
|
@@ -8317,11 +9359,25 @@ function bindUi() {
|
|
|
8317
9359
|
$('btn-model-refresh').addEventListener('click', loadSessionModels)
|
|
8318
9360
|
const input = $('composer-input')
|
|
8319
9361
|
input.addEventListener('input', () => autosize(input))
|
|
9362
|
+
window.DshSlashSuggestions?.mount({
|
|
9363
|
+
input, t,
|
|
9364
|
+
panel: $('composer-command-list'), chipClass: 'menu-chip', chipAttribute: 'data-cmd',
|
|
9365
|
+
context() {
|
|
9366
|
+
const connection = captureConnection(), sessionId = state.current, history = state.history
|
|
9367
|
+
if (!sessionId || state.byId.get(sessionId)?.origin === 'subagent') return null
|
|
9368
|
+
return {
|
|
9369
|
+
sessionId, url: path => connection.server + path,
|
|
9370
|
+
headers: { authorization: 'Bearer ' + connection.token, ...clientIdHeaders() },
|
|
9371
|
+
valid: () => connection.valid() && state.current === sessionId && state.history === history,
|
|
9372
|
+
}
|
|
9373
|
+
},
|
|
9374
|
+
readSkills: sessionId => rpc('skills.list', { sessionId }, 5000),
|
|
9375
|
+
})
|
|
8320
9376
|
$('btn-fs-toggle').addEventListener('click', () => setComposerFullscreen(!$('composer-wrap').classList.contains('fs')))
|
|
8321
9377
|
bindComposerFullscreenGesture()
|
|
8322
9378
|
updateComposerFullscreenButton()
|
|
8323
9379
|
input.addEventListener('keydown', (e) => {
|
|
8324
|
-
if (e.key !== 'Enter' || e.isComposing) return
|
|
9380
|
+
if (e.defaultPrevented || e.key !== 'Enter' || e.isComposing || composerTools?.keydown(e)) return
|
|
8325
9381
|
if (isMobileDevice() && mobileEnterAction() !== 'send') return
|
|
8326
9382
|
if (!e.shiftKey) { e.preventDefault(); sendMessage() }
|
|
8327
9383
|
})
|
|
@@ -8418,6 +9474,56 @@ function bindUi() {
|
|
|
8418
9474
|
$('group-drawer-trigger').addEventListener('click', () => { groupDrawerOpen() ? closeGroupDrawer() : openGroupDrawer() })
|
|
8419
9475
|
$('group-drawer-close').addEventListener('click', () => closeGroupDrawer())
|
|
8420
9476
|
$('group-drawer-backdrop').addEventListener('click', () => closeGroupDrawer())
|
|
9477
|
+
$('group-drawer-collapse').addEventListener('click', () => setGroupDrawerPanel(''))
|
|
9478
|
+
$('group-drawer-shortcut-options').addEventListener('change', (event) => {
|
|
9479
|
+
const checkbox = event.target.closest('input[data-drawer-shortcut-setting]')
|
|
9480
|
+
if (!checkbox) return
|
|
9481
|
+
const hidden = readGroupDrawerHiddenShortcuts()
|
|
9482
|
+
const key = checkbox.dataset.drawerShortcutSetting
|
|
9483
|
+
if (checkbox.checked) hidden.delete(key)
|
|
9484
|
+
else hidden.add(key)
|
|
9485
|
+
if (!saveGroupDrawerShortcuts(hidden)) checkbox.checked = !checkbox.checked
|
|
9486
|
+
})
|
|
9487
|
+
$('group-drawer-reset-shortcuts').addEventListener('click', () => {
|
|
9488
|
+
if (saveGroupDrawerShortcuts(new Set())) renderGroupDrawerEditor()
|
|
9489
|
+
})
|
|
9490
|
+
$('session-open-drawer').addEventListener('click', () => {
|
|
9491
|
+
$('session-actions').close()
|
|
9492
|
+
$('btn-session-more').focus({ preventScroll: true })
|
|
9493
|
+
openGroupDrawer()
|
|
9494
|
+
})
|
|
9495
|
+
$('group-drawer-host').addEventListener('click', () => {
|
|
9496
|
+
closeGroupDrawer({ restoreFocus: false })
|
|
9497
|
+
showView('view-settings')
|
|
9498
|
+
showSettingsPage('servers')
|
|
9499
|
+
})
|
|
9500
|
+
$('group-drawer').addEventListener('click', (event) => {
|
|
9501
|
+
const target = event.target.closest('[data-drawer-open-panel], [data-drawer-view], [data-drawer-setting], [data-drawer-session]')
|
|
9502
|
+
if (!target) return
|
|
9503
|
+
const { drawerOpenPanel, drawerView, drawerSetting, drawerSession } = target.dataset
|
|
9504
|
+
if (drawerOpenPanel) {
|
|
9505
|
+
setGroupDrawerPanel($('group-drawer').dataset.panel === drawerOpenPanel ? '' : drawerOpenPanel)
|
|
9506
|
+
} else if (drawerSetting && SETTINGS_GROUPS.includes(drawerSetting)) {
|
|
9507
|
+
showView('view-settings')
|
|
9508
|
+
showSettingsPage(drawerSetting)
|
|
9509
|
+
} else if (drawerView) {
|
|
9510
|
+
closeGroupDrawer({ restoreFocus: false })
|
|
9511
|
+
showView(drawerView)
|
|
9512
|
+
} else if (state.byId.has(drawerSession)) {
|
|
9513
|
+
const current = drawerSession === state.current && !$('view-session').classList.contains('hidden')
|
|
9514
|
+
closeGroupDrawer({ restoreFocus: current })
|
|
9515
|
+
if (!current) void openSession(drawerSession)
|
|
9516
|
+
}
|
|
9517
|
+
})
|
|
9518
|
+
$('group-drawer-update')?.addEventListener('click', () => {
|
|
9519
|
+
closeGroupDrawer({ restoreFocus: false })
|
|
9520
|
+
openUpdateSettings()
|
|
9521
|
+
})
|
|
9522
|
+
$('group-drawer-operations-open').addEventListener('click', () => {
|
|
9523
|
+
closeGroupDrawer()
|
|
9524
|
+
if (window.DshWorkflow?.isMounted()) void window.DshWorkflow.showOperations()
|
|
9525
|
+
else showView('view-activity')
|
|
9526
|
+
})
|
|
8421
9527
|
$('group-drawer-list').addEventListener('click', (e) => {
|
|
8422
9528
|
const option = e.target.closest('[data-quick-group]')
|
|
8423
9529
|
if (!option) return
|
|
@@ -8429,6 +9535,12 @@ function bindUi() {
|
|
|
8429
9535
|
closeGroupDrawer({ restoreFocus: false })
|
|
8430
9536
|
showView('view-settings')
|
|
8431
9537
|
showSettingsPage('servers')
|
|
9538
|
+
const addresses = $('workflow-settings-servers-local')
|
|
9539
|
+
if (addresses) {
|
|
9540
|
+
addresses.open = true
|
|
9541
|
+
addresses.querySelector('summary')?.focus({ preventScroll: true })
|
|
9542
|
+
addresses.scrollIntoView({ block: 'start' })
|
|
9543
|
+
}
|
|
8432
9544
|
})
|
|
8433
9545
|
document.addEventListener('keydown', keepGroupDrawerFocus)
|
|
8434
9546
|
document.addEventListener('click', (e) => {
|
|
@@ -8585,6 +9697,7 @@ window.addEventListener('dsh-native-insets', applyNativeInsets)
|
|
|
8585
9697
|
async function boot() {
|
|
8586
9698
|
initToken()
|
|
8587
9699
|
bindUi()
|
|
9700
|
+
if (typeof initBcFeatures === 'function') initBcFeatures()
|
|
8588
9701
|
syncBgConfig()
|
|
8589
9702
|
renderAnnouncementBoard()
|
|
8590
9703
|
renderLangBtn()
|
|
@@ -8612,8 +9725,10 @@ async function boot() {
|
|
|
8612
9725
|
startAnnouncementPolling()
|
|
8613
9726
|
scheduleStartupNotices()
|
|
8614
9727
|
renderPending()
|
|
9728
|
+
initTurnDiffSetting()
|
|
8615
9729
|
pendingNavigationReady = true
|
|
8616
9730
|
void openPendingNavigation()
|
|
9731
|
+
window.dispatchEvent(new Event('dsh-relay-activation'))
|
|
8617
9732
|
}
|
|
8618
9733
|
|
|
8619
9734
|
document.addEventListener('DOMContentLoaded', boot)
|
|
@@ -8624,10 +9739,12 @@ function mountWorkflow() {
|
|
|
8624
9739
|
desktop: false,
|
|
8625
9740
|
start: () => { if (!$('view-activity').classList.contains('hidden')) showView('view-home') },
|
|
8626
9741
|
snapshot: () => ({ token: !!state.token, host: currentServerEntry()?.note || state.server || location.host,
|
|
9742
|
+
connectionIssue: activeConnectionIssue(), address: state.server || location.host, offline: navigator.onLine === false,
|
|
8627
9743
|
gateway: activeGatewayHealth()?.ok || !!state.streamsOk?.mux, dsh: dshReachable(),
|
|
8628
9744
|
mux: !!state.streamsOk?.mux, hostEvents: !!state.streamsOk?.host,
|
|
8629
9745
|
pending: state.approvals.length + state.questions.length, busy: composerIsBusy(), sending: composerSending }),
|
|
8630
9746
|
settings: name => { showView('view-settings'); showSettingsPage(name) },
|
|
9747
|
+
cloudRelayReady: () => pendingNavigationReady,
|
|
8631
9748
|
plugins: () => showView('view-plugins'), models: loadSessionModels, send: sendMessage,
|
|
8632
9749
|
feedback: openFeedbackModal,
|
|
8633
9750
|
doctor: openDoctor,
|
|
@@ -8642,9 +9759,10 @@ function mountWorkflow() {
|
|
|
8642
9759
|
state.workspaceFilter=value.workspace.workspaceId;closeWorkspaceModal();await newSession()
|
|
8643
9760
|
}catch(error){if(connection.valid())toast(error.message,'err')}
|
|
8644
9761
|
},
|
|
8645
|
-
command: runSlashCommand, refresh: refreshAll, retry: () => { startOverviewDetection(true); void refreshAll() },
|
|
9762
|
+
command: runSlashCommand, refresh: refreshAll, retry: () => { openStreams(); startOverviewDetection(true); void refreshAll() },
|
|
8646
9763
|
operations: () => { const connection=captureConnection(); return { url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid } },
|
|
8647
|
-
relay: () => { const connection=captureConnection(); return { url:()=>adminApiUrl('/admin/api/relay'),headers:{authorization:'Bearer '+connection.token},valid:connection.valid,connected:!!connection.token,setupId:relaySetupFor(connection) } },
|
|
9764
|
+
relay: () => { const connection=captureConnection(); return { url:()=>adminApiUrl('/admin/api/relay'),headers:{authorization:'Bearer '+connection.token,...clientIdHeaders()},valid:connection.valid,connected:!!connection.token,setupId:relaySetupFor(connection) } },
|
|
9765
|
+
syncRelayActivation: CAP?.isNativePlatform?.() ? status => syncRelayActivation(status.activationId, true) : undefined,
|
|
8648
9766
|
e2eeAutoPaired: saveAutoPairedRelay,
|
|
8649
9767
|
e2eeScan: () => scanPair('CAMERA'),
|
|
8650
9768
|
e2eeConnect: (origin, connection) => {
|
|
@@ -8686,7 +9804,7 @@ function mountWorkflow() {
|
|
|
8686
9804
|
|
|
8687
9805
|
function mountOnboarding() {
|
|
8688
9806
|
window.DshOnboarding?.mount({
|
|
8689
|
-
snapshot: () => ({ connection: connectionGeneration, session: state.current,
|
|
9807
|
+
snapshot: () => ({ connection: connectionGeneration, session: state.current, hasSessions: state.sessions.length > 0,
|
|
8690
9808
|
connected: navigator.onLine !== false && !!state.token && dshReachable()
|
|
8691
9809
|
&& (!!state.streamsOk?.mux || (state.streamMode === 'poll' && !!state.hostInfo)),
|
|
8692
9810
|
sessionReady: state.sessionRecovery.status === 'ready' && !state.history.loading }),
|