dsh-remote-plugin 0.8.8 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +16 -5
- package/README.md +15 -4
- package/apk/dsh-remote.apk +0 -0
- package/gateway.cjs +583 -84
- package/index.mjs +1 -0
- package/package.json +8 -3
- package/public/activity.js +97 -10
- package/public/admin.html +34 -33
- package/public/admin.js +10 -2
- package/public/announcements.json +36 -0
- package/public/app.js +1564 -226
- package/public/bc-integration.css +81 -0
- package/public/build.json +2 -2
- package/public/composer-tools.css +184 -0
- package/public/composer-tools.js +888 -0
- package/public/desktop/desktop.html +94 -73
- package/public/desktop/desktop.js +726 -83
- package/public/e2ee-config.js +5 -0
- package/public/e2ee-transport.js +23 -4
- package/public/file-inbox.js +77 -18
- package/public/genui.css +10 -0
- package/public/genui.js +22 -4
- package/public/history.js +114 -17
- package/public/host-queue.js +232 -0
- package/public/host-schedule.js +301 -0
- package/public/host-state.css +19 -0
- package/public/index.html +332 -140
- package/public/md.js +21 -1
- package/public/network.js +33 -1
- package/public/onboarding.js +3 -3
- package/public/operations.js +4 -3
- package/public/plan-review.css +297 -0
- package/public/plan-review.js +642 -0
- package/public/plugin.html +29 -28
- package/public/relay-autopair.js +30 -10
- package/public/relay-devices.js +7 -3
- package/public/relay-settings.css +11 -0
- package/public/relay-settings.js +372 -30
- package/public/session-cache.js +85 -0
- package/public/session-management.css +61 -0
- package/public/session-management.js +742 -0
- package/public/session-search.css +137 -0
- package/public/session-search.js +977 -0
- package/public/skins/blue-fish/preview.html +3 -3
- package/public/skins/bocchi/preview.html +5 -5
- package/public/skins/kita/preview.html +6 -6
- package/public/skins/miku/SOURCES.json +10 -0
- package/public/skins/miku/chibi.png +0 -0
- package/public/skins/miku/preview.html +33 -0
- package/public/skins/miku/skin.css +82 -0
- package/public/skins/nijika/preview.html +6 -6
- package/public/skins/penguin/preview.html +3 -3
- package/public/skins/ryo/preview.html +6 -6
- package/public/slash-suggestions.js +15 -3
- package/public/sponsor-entry.js +11 -3
- package/public/styles.css +141 -21
- package/public/subagents.css +5 -0
- package/public/subagents.js +52 -0
- package/public/theme-vars.css +65 -1
- package/public/theme.js +4 -3
- package/public/turn-diff.css +323 -0
- package/public/turn-diff.js +778 -0
- package/public/update.json +12 -12
- package/public/version.json +1 -1
- package/public/workflow.css +305 -34
- package/public/workflow.js +141 -41
|
@@ -40,7 +40,8 @@ const THEME_META = [
|
|
|
40
40
|
{ id: 'nijika', sw: ['#FFF3D5', '#FFFFFF', '#94600C'] },
|
|
41
41
|
{ id: 'ryo', sw: ['#E9F1FA', '#FFFFFF', '#315D91'] },
|
|
42
42
|
{ id: 'kita', sw: ['#FFE9E5', '#FFFFFF', '#B6373C'] },
|
|
43
|
-
{ id: 'penguin-logistics', sw: ['#12161B', '#1D252E', '#E9B66F'] }
|
|
43
|
+
{ id: 'penguin-logistics', sw: ['#12161B', '#1D252E', '#E9B66F'] },
|
|
44
|
+
{ id: 'miku', sw: ['#F3FFFC', '#FFFFFF', '#126D69'] }
|
|
44
45
|
]
|
|
45
46
|
function themeGet() {
|
|
46
47
|
const v = LS.get('dshTheme', '')
|
|
@@ -88,7 +89,6 @@ const state = {
|
|
|
88
89
|
questions: [],
|
|
89
90
|
queues: {},
|
|
90
91
|
sessionActivity: new Set(),
|
|
91
|
-
queueSteering: {},
|
|
92
92
|
compactionBootAt: Date.now(),
|
|
93
93
|
compactions: {},
|
|
94
94
|
pendingCommands: {},
|
|
@@ -109,6 +109,7 @@ const state = {
|
|
|
109
109
|
workspaces: [],
|
|
110
110
|
wb: { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false },
|
|
111
111
|
archivedIds: [],
|
|
112
|
+
pinnedIds: [],
|
|
112
113
|
view: 'sessions',
|
|
113
114
|
subagentSessions: {}
|
|
114
115
|
}
|
|
@@ -133,10 +134,10 @@ for (const key of ['server', 'token']) {
|
|
|
133
134
|
state.current = null; state.history = emptyDesktopHistory(); state.subagentSessions = {}; window.DshSubagents?.reset()
|
|
134
135
|
state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
|
|
135
136
|
state.approvals = []; state.questions = []; state.questionModal = null
|
|
136
|
-
state.queues = {}; state.
|
|
137
|
+
state.queues = {}; state.compactions = {}; state.compactionTerminals = {}; state.compactionSeqs = {}; state.compactionBootAt = Date.now(); state.pendingCommands = {}; state.sessionTurnTimes = {}
|
|
137
138
|
state.sessionActivity = new Set()
|
|
138
139
|
state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
|
|
139
|
-
state.workspaces = []; state.archivedIds = []; state.wb = { bound: false, path: '', projects: null }
|
|
140
|
+
state.workspaces = []; state.archivedIds = []; state.pinnedIds = []; state.wb = { bound: false, path: '', projects: null }
|
|
140
141
|
window.DshPluginCenter?.close()
|
|
141
142
|
window.DshInsights?.close()
|
|
142
143
|
window.DshExtensions?.close()
|
|
@@ -763,19 +764,20 @@ async function rpc(method, payload = {}, timeoutMs = 45000, cancellation = null)
|
|
|
763
764
|
else if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
|
|
764
765
|
opts.signal = AbortSignal.timeout(timeoutMs)
|
|
765
766
|
}
|
|
766
|
-
const operation = window.DshOperations?.supports(method) && activeGatewayCapability('operations') === true
|
|
767
|
+
const operation = window.DshOperations?.supports(method) && (window.DshOperations.requiresReceipt?.(method) || activeGatewayCapability('operations') === true)
|
|
767
768
|
const connection = operation ? captureConnection() : null
|
|
768
769
|
const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
|
|
769
770
|
const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
|
|
770
771
|
diagnostic?.end({phase:'response',httpStatus:res.status})
|
|
771
772
|
if (res.status === 401) throw new Error('AUTH')
|
|
772
|
-
if (!res.ok)
|
|
773
|
+
if (!res.ok) { const error = new Error('HTTP ' + res.status); error.status = res.status; throw error }
|
|
773
774
|
const full = await res.json()
|
|
774
775
|
if (!full?.result) throw new Error('bad response')
|
|
775
776
|
if (!full.result.ok) {
|
|
776
777
|
const err = full.result.error || {}
|
|
777
778
|
const error = new Error(err.code === 'session/migration-required' ? t('session.migrationRequired') : err.message || 'dsh error')
|
|
778
779
|
error.code = err.code
|
|
780
|
+
error.rpcRejected = true
|
|
779
781
|
throw error
|
|
780
782
|
}
|
|
781
783
|
diagnostic?.end({phase:'complete'})
|
|
@@ -883,6 +885,23 @@ function serverIdentity(url, token) {
|
|
|
883
885
|
}
|
|
884
886
|
function serverKey(server) { return serverIdentity(server?.url ?? server, server?.token) }
|
|
885
887
|
function serverToken(server) { return normalizedServerToken(server?.token) }
|
|
888
|
+
function groupToken(group = state.activeGroup) {
|
|
889
|
+
const tokens = [...new Set(groupServers(group).map(serverToken).filter(Boolean))]
|
|
890
|
+
return tokens.length === 1 ? tokens[0] : ''
|
|
891
|
+
}
|
|
892
|
+
function syncGroupToken(group, token) {
|
|
893
|
+
const value = normalizedServerToken(token)
|
|
894
|
+
if (!group || !value) return 0
|
|
895
|
+
let changed = 0
|
|
896
|
+
for (const server of groupServers(group)) {
|
|
897
|
+
if (serverToken(server) === value) continue
|
|
898
|
+
server.token = value
|
|
899
|
+
delete server.cacheRelayPin
|
|
900
|
+
delete server.cacheRelayOrigin
|
|
901
|
+
changed++
|
|
902
|
+
}
|
|
903
|
+
return changed
|
|
904
|
+
}
|
|
886
905
|
function currentServerEntry() {
|
|
887
906
|
return state.servers.find(s => s.url === state.server && serverToken(s) === state.token)
|
|
888
907
|
|| state.servers.find(s => s.url === state.server)
|
|
@@ -892,7 +911,7 @@ function setCurrentAccessToken(value) {
|
|
|
892
911
|
const token = normalizedServerToken(value)
|
|
893
912
|
if (!token) return false
|
|
894
913
|
const current = currentServerEntry()
|
|
895
|
-
|
|
914
|
+
syncGroupToken(current?.group || state.activeGroup, token)
|
|
896
915
|
state.token = token
|
|
897
916
|
LS.set('token', token)
|
|
898
917
|
saveServers()
|
|
@@ -952,22 +971,15 @@ function serverCandidates() {
|
|
|
952
971
|
if (location.origin && !list.some(s => s.url === location.origin)) list.push({ id: 'origin', url: location.origin, token: state.token, origin: true })
|
|
953
972
|
return list
|
|
954
973
|
}
|
|
955
|
-
|
|
974
|
+
function pingServer(base, token) {
|
|
956
975
|
const u = String(base || '').replace(/\/+$/, '')
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
const timer = setTimeout(() => ctrl.abort(), 3500)
|
|
961
|
-
try {
|
|
962
|
-
const res = await fetch(u + '/health?probe=live&t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
|
|
963
|
-
if (!res.ok) return Infinity
|
|
964
|
-
const health = await res.json().catch(() => null)
|
|
965
|
-
if (health && typeof health === 'object') {
|
|
976
|
+
return DshNetwork.probeGateway(u, {
|
|
977
|
+
headers: token === undefined ? undefined : { authorization: token ? 'Bearer ' + token : '', 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
|
|
978
|
+
onHealth: health => {
|
|
966
979
|
state.gatewayHealth[u] = health
|
|
967
980
|
renderOverviewDesktop()
|
|
968
|
-
}
|
|
969
|
-
|
|
970
|
-
} catch { return Infinity } finally { clearTimeout(timer) }
|
|
981
|
+
},
|
|
982
|
+
})
|
|
971
983
|
}
|
|
972
984
|
function activeGatewayCapability(name) {
|
|
973
985
|
const capabilities = activeGatewayHealth()?.capabilities
|
|
@@ -1000,7 +1012,7 @@ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
|
|
|
1000
1012
|
let best = null
|
|
1001
1013
|
let ms = Infinity
|
|
1002
1014
|
if (state.autoSelect[state.activeGroup] !== false) {
|
|
1003
|
-
const measured = await Promise.all(candidates.map(async
|
|
1015
|
+
const measured = await Promise.all(candidates.map(async server => [server, await pingServer(server.url, server.token)]))
|
|
1004
1016
|
if (!valid()) return null
|
|
1005
1017
|
for (const [server, latency] of measured) state.serverLatency[serverKey(server)] = latency
|
|
1006
1018
|
best = candidates.filter(server => Number.isFinite(state.serverLatency[serverKey(server)])).sort((a, b) => state.serverLatency[serverKey(a)] - state.serverLatency[serverKey(b)])[0] || null
|
|
@@ -1140,9 +1152,12 @@ function renderServers() {
|
|
|
1140
1152
|
const list = groupServers(g)
|
|
1141
1153
|
const auto = state.autoSelect[g] !== false
|
|
1142
1154
|
const activeManual = state.groupActive[g] || ''
|
|
1155
|
+
const tokens = new Set(list.map(serverToken).filter(Boolean))
|
|
1156
|
+
const mixedToken = tokens.size > 1
|
|
1143
1157
|
return `<div class="ds-srv-group" data-group="${esc(g)}">
|
|
1144
1158
|
<div class="ds-srv-head">
|
|
1145
1159
|
<button class="ds-srv-name" data-group-name="${esc(g)}" title="${t('ds.groupsSwitchHint')}"><span class="ds-srv-label">${g === state.activeGroup ? '▾' : '▸'} ${esc(g)}</span><span class="ds-srv-count">${list.length}</span></button>
|
|
1160
|
+
${mixedToken ? `<button class="ds-mini" data-sync-group="${esc(g)}" title="${I18N.lang === 'en' ? 'This group has mixed tokens; use the current connection token for all addresses' : '本组地址令牌不一致,点击用当前连接令牌统一'}">${I18N.lang === 'en' ? 'Sync token' : '统一令牌'}</button>` : ''}
|
|
1146
1161
|
<button class="ds-mini" data-speed-group="${esc(g)}" title="${t('ds.speedTest')}">⚡</button>
|
|
1147
1162
|
<label class="ds-switch" title="${t('ds.groupsAutoSelect')}"><input type="checkbox" data-auto-group="${esc(g)}" ${auto ? 'checked' : ''}><span class="ds-slider"></span></label>
|
|
1148
1163
|
${g !== '默认' ? `<button class="ds-mini" data-del-group="${esc(g)}" title="${t('ds.groupsDelete')}">✕</button>` : ''}
|
|
@@ -1172,6 +1187,20 @@ function renderServers() {
|
|
|
1172
1187
|
b.addEventListener('dblclick', () => renameGroup(b.dataset.groupName))
|
|
1173
1188
|
})
|
|
1174
1189
|
box.querySelectorAll('[data-speed-group]').forEach(b => b.addEventListener('click', () => { state.activeGroup = b.dataset.speedGroup; saveServers(); selectFastestServer({ silent: false }) }))
|
|
1190
|
+
box.querySelectorAll('[data-sync-group]').forEach(b => b.addEventListener('click', () => {
|
|
1191
|
+
const group = b.dataset.syncGroup
|
|
1192
|
+
const token = normalizedServerToken(state.token)
|
|
1193
|
+
if (!token) return toast(I18N.lang === 'en' ? 'No current token to sync.' : '当前没有可用的令牌。', 'err')
|
|
1194
|
+
const count = groupServers(group).length
|
|
1195
|
+
const message = I18N.lang === 'en'
|
|
1196
|
+
? `Use the current connection token for all ${count} addresses in group "${group}"?`
|
|
1197
|
+
: `用当前连接令牌统一组「${group}」的 ${count} 个地址?`
|
|
1198
|
+
if (!window.confirm(message)) return
|
|
1199
|
+
const changed = syncGroupToken(group, token)
|
|
1200
|
+
saveServers(); renderServers()
|
|
1201
|
+
toast(I18N.lang === 'en' ? `Token synced for ${changed} address(es).` : `已同步 ${changed} 个地址的令牌。`, 'ok')
|
|
1202
|
+
if (state.token) selectFastestServer({ silent: true })
|
|
1203
|
+
}))
|
|
1175
1204
|
box.querySelectorAll('[data-auto-group]').forEach(chk => chk.addEventListener('change', (e) => {
|
|
1176
1205
|
const g = e.target.dataset.autoGroup
|
|
1177
1206
|
state.autoSelect[g] = e.target.checked
|
|
@@ -1213,10 +1242,17 @@ async function addServer() {
|
|
|
1213
1242
|
if (!raw) return toast(t('ds.serversNeedAddress'), 'err')
|
|
1214
1243
|
try { const u = new URL(raw); if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error('bad') }
|
|
1215
1244
|
catch { return toast(t('ds.serversBadProtocol'), 'err') }
|
|
1216
|
-
const
|
|
1245
|
+
const group = state.activeGroup
|
|
1246
|
+
const tokens = new Set(groupServers(group).map(serverToken).filter(Boolean))
|
|
1247
|
+
if (tokens.size > 1) {
|
|
1248
|
+
return toast(I18N.lang === 'en'
|
|
1249
|
+
? 'This group has mixed tokens. Unify them before adding another address.'
|
|
1250
|
+
: '本组地址令牌不一致,请先点击「统一令牌」再添加地址。', 'err')
|
|
1251
|
+
}
|
|
1252
|
+
const token = tokens.size === 1 ? [...tokens][0] : normalizedServerToken(state.token)
|
|
1217
1253
|
if (state.servers.some(s => serverIdentity(s.url, serverToken(s)) === serverIdentity(raw, token))) return toast(t('ds.serversDuplicate'), 'err')
|
|
1218
1254
|
const note = (prompt(t('ds.serversPromptNote')) || '').trim()
|
|
1219
|
-
state.servers.push({ id: newServerId(), url: raw, note, group
|
|
1255
|
+
state.servers.push({ id: newServerId(), url: raw, note, group, token })
|
|
1220
1256
|
saveServers()
|
|
1221
1257
|
if (input) input.value = ''
|
|
1222
1258
|
renderServers()
|
|
@@ -1240,7 +1276,9 @@ function editServer(id) {
|
|
|
1240
1276
|
if (group === null) return
|
|
1241
1277
|
const wasActive = state.server === s.url && state.token === serverToken(s)
|
|
1242
1278
|
const changedActiveUrl = wasActive && state.server !== raw
|
|
1279
|
+
const previousToken = serverToken(s)
|
|
1243
1280
|
s.url = raw; s.note = note.trim(); s.group = ensureGroup(group.trim() || '默认'); s.token = token
|
|
1281
|
+
if (previousToken !== token) syncGroupToken(s.group, token)
|
|
1244
1282
|
if (wasActive) {
|
|
1245
1283
|
if (changedActiveUrl) resetFsForServerDesktop()
|
|
1246
1284
|
state.server = raw
|
|
@@ -1255,6 +1293,7 @@ function removeServer(id) {
|
|
|
1255
1293
|
if (!s) return
|
|
1256
1294
|
void window.DshImageCache?.clear(historyCacheScope(s.url,serverToken(s)))
|
|
1257
1295
|
void window.DshHistory.cacheClear(historyCacheScope(s.url,serverToken(s)))
|
|
1296
|
+
clearSessionCache(historyCacheScope(s.url,serverToken(s)))
|
|
1258
1297
|
state.servers = state.servers.filter(x => x.id !== id)
|
|
1259
1298
|
const wasActive = state.server === s.url && state.token === serverToken(s)
|
|
1260
1299
|
for (const g of state.groups) if (state.groupActive[g] === id) state.groupActive[g] = ''
|
|
@@ -1618,6 +1657,7 @@ setInterval(sessionSyncTick, 15000)
|
|
|
1618
1657
|
function onMuxFrame(full) {
|
|
1619
1658
|
const f = full.payload
|
|
1620
1659
|
if (!f) return
|
|
1660
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.handleFrame?.(full)
|
|
1621
1661
|
if (f.type === 'session/reasoning') {
|
|
1622
1662
|
if (f.sessionId === state.current) { applyReasoningBaseline(f.partialReasoning); scheduleReasoningRender() }
|
|
1623
1663
|
return
|
|
@@ -1634,22 +1674,37 @@ function onMuxFrame(full) {
|
|
|
1634
1674
|
if (f.type === 'question/requested') {
|
|
1635
1675
|
state.questions = state.questions.filter(q => q.rpcId !== full.rpcId)
|
|
1636
1676
|
state.questions.push({ ...f, rpcId: full.rpcId })
|
|
1637
|
-
renderNotifStack()
|
|
1677
|
+
renderNotifStack(); if (typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
1638
1678
|
return
|
|
1639
1679
|
}
|
|
1640
1680
|
if (f.type === 'question/resolved') {
|
|
1641
1681
|
state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId)
|
|
1642
1682
|
if (state.questionModal?.rpcId === f.questionRpcId) { $('modal-question').classList.add('hidden'); state.questionModal = null }
|
|
1643
|
-
renderNotifStack(); return
|
|
1683
|
+
renderNotifStack(); if (typeof refreshPlanReview === 'function') refreshPlanReview(); return
|
|
1684
|
+
}
|
|
1685
|
+
if (f.type === 'session/queue') {
|
|
1686
|
+
if (hostQueue?.accept(f.sessionId, f.seq) !== false) state.queues[f.sessionId] = f.items || []
|
|
1687
|
+
renderQueue(); return
|
|
1688
|
+
}
|
|
1689
|
+
if (f.type === 'session/projection') {
|
|
1690
|
+
applyProjection(f.sessionId, f.key, f.value, f.seq)
|
|
1691
|
+
if (f.key === 'plan' && f.sessionId === state.current && typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
1692
|
+
if (f.key === 'conversationContinuation' && f.sessionId === state.current) renderHistory()
|
|
1693
|
+
if (f.key === 'agentTeam') window.DshSubagents?.updateTeam?.(f.sessionId, f.value, f.seq)
|
|
1694
|
+
return
|
|
1644
1695
|
}
|
|
1645
|
-
if (f.type === 'session/queue') { state.queues[f.sessionId] = f.items || []; renderQueue(); return }
|
|
1646
|
-
if (f.type === 'session/projection') { applyProjection(f.sessionId, f.key, f.value, f.seq); return }
|
|
1647
1696
|
if (f.type === 'stream/error') toast(f.error?.message || 'stream error', 'err')
|
|
1648
1697
|
if (f.type === 'session/stream-error' && f.sessionId === state.current) { const message=f.error?.code==='session/migration-required'?t('session.migrationRequired'):f.error?.message;setSessionRecovery('error',message);toast(message,'err') }
|
|
1649
1698
|
}
|
|
1650
1699
|
function onHostFrame(full) {
|
|
1651
1700
|
const f = full.payload
|
|
1652
1701
|
if (!f) return
|
|
1702
|
+
if (f.type === 'schedule/changed') { void hostSchedule?.refresh(true); return }
|
|
1703
|
+
if (f.type === 'host/pinned-sessions-changed') {
|
|
1704
|
+
state.pinnedIds = Array.isArray(f.pinnedSessionIds) ? f.pinnedSessionIds : []
|
|
1705
|
+
renderSessions()
|
|
1706
|
+
return
|
|
1707
|
+
}
|
|
1653
1708
|
if (['host/session-added', 'host/session-removed', 'host/workspace-changed', 'host/workspace-removed', 'host/workspace-order-changed', 'host/archived-sessions-changed'].includes(f.type)) scheduleSessionsRefresh()
|
|
1654
1709
|
if (f.type === 'host/session-activity') {
|
|
1655
1710
|
const session = state.byId.get(f.sessionId)
|
|
@@ -1866,8 +1921,10 @@ function rememberRuntimeError(sessionId, message) {
|
|
|
1866
1921
|
if (sessionId === state.current) { renderHistory(); scheduleSessionSync(sessionId) }
|
|
1867
1922
|
}
|
|
1868
1923
|
function resyncAfterStreamOpen() {
|
|
1924
|
+
if (typeof hostSchedule !== 'undefined') void hostSchedule?.refresh(true)
|
|
1869
1925
|
if (!state.current || Date.now() - state.lastStreamResyncAt < 1200) return
|
|
1870
1926
|
state.lastStreamResyncAt = Date.now()
|
|
1927
|
+
if (typeof hostQueue !== 'undefined') hostQueue?.reconnect()
|
|
1871
1928
|
void refreshSessions().then(() => resyncCurrentSession())
|
|
1872
1929
|
}
|
|
1873
1930
|
function proj(s, key, d) { return s?.projections?.values?.[key] ?? d }
|
|
@@ -1950,6 +2007,8 @@ function setGoalCollapsed(sessionId, goal, collapsed) {
|
|
|
1950
2007
|
LS.set(COLLAPSED_GOALS_KEY, JSON.stringify(next.slice(-100)))
|
|
1951
2008
|
}
|
|
1952
2009
|
function onSessionEvent(sessionId, event, meta = {}) {
|
|
2010
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.handleEvent?.(sessionId, event)
|
|
2011
|
+
if (typeof turnDiffController !== 'undefined') turnDiffController?.handleEvent?.(sessionId, event)
|
|
1953
2012
|
if (collectApprovalEvent(sessionId, event)) renderApprovalRecordsDesktop()
|
|
1954
2013
|
observeCompactionEvent(sessionId, event, meta)
|
|
1955
2014
|
const failedSession = state.byId.get(sessionId)
|
|
@@ -2011,11 +2070,12 @@ async function refreshSessions() {
|
|
|
2011
2070
|
state.subagentSessions[id] = merged
|
|
2012
2071
|
}
|
|
2013
2072
|
applyPendingProjections()
|
|
2014
|
-
|
|
2073
|
+
writeSessionCache(state.sessions)
|
|
2015
2074
|
if(typeof window!=='undefined')window.DshDoctorEntry?.consumeSessionLink(openSession,state.byId)
|
|
2016
2075
|
renderSessions()
|
|
2017
2076
|
scheduleWorkbenchRefresh()
|
|
2018
2077
|
renderOverviewDesktop()
|
|
2078
|
+
if (typeof sessionManager !== 'undefined') sessionManager?.hydrate?.()
|
|
2019
2079
|
}
|
|
2020
2080
|
function sessionCwd(s) { return typeof s?.cwd === 'string' ? s.cwd.trim() : '' }
|
|
2021
2081
|
function sessionWorkspaceLabel(s) {
|
|
@@ -2048,15 +2108,19 @@ function workspaceDisplayName(label) {
|
|
|
2048
2108
|
}
|
|
2049
2109
|
function sortedSessions() {
|
|
2050
2110
|
const items = topLevelSessions()
|
|
2111
|
+
const pinned = new Set(state.pinnedIds || [])
|
|
2112
|
+
const pinRank = session => pinned.has(session.sessionId) ? 0 : 1
|
|
2051
2113
|
if (state.sessionSort === 'workspace') {
|
|
2052
2114
|
return items.sort((a, b) => {
|
|
2115
|
+
const byPin = pinRank(a) - pinRank(b)
|
|
2116
|
+
if (byPin) return byPin
|
|
2053
2117
|
const aw = sessionCwd(a) || '\uffff'
|
|
2054
2118
|
const bw = sessionCwd(b) || '\uffff'
|
|
2055
2119
|
const byWorkspace = aw.localeCompare(bw, undefined, { numeric: true, sensitivity: 'base' })
|
|
2056
2120
|
return byWorkspace || (sessionSortTime(b) - sessionSortTime(a))
|
|
2057
2121
|
})
|
|
2058
2122
|
}
|
|
2059
|
-
return items.sort((a, b) => sessionSortTime(b) - sessionSortTime(a))
|
|
2123
|
+
return items.sort((a, b) => pinRank(a) - pinRank(b) || sessionSortTime(b) - sessionSortTime(a))
|
|
2060
2124
|
}
|
|
2061
2125
|
function renderSessions() {
|
|
2062
2126
|
const allItems = sortedSessions()
|
|
@@ -2064,6 +2128,7 @@ function renderSessions() {
|
|
|
2064
2128
|
if (state.wb.bound && state.wb.projects) for (const w of state.wb.projects) for (const id of (w.sessionIds || [])) wbIds.add(id)
|
|
2065
2129
|
const root = state.wb.bound ? state.wb.path : ''
|
|
2066
2130
|
const archivedSet = new Set(state.archivedIds || [])
|
|
2131
|
+
const pinnedSet = new Set(state.pinnedIds || [])
|
|
2067
2132
|
const visible = allItems.filter(s => {
|
|
2068
2133
|
if (!state.wb.bound) return true
|
|
2069
2134
|
if (archivedSet.has(s.sessionId)) return true
|
|
@@ -2077,7 +2142,7 @@ function renderSessions() {
|
|
|
2077
2142
|
const workspaceName = workspaceDisplayName(workspace)
|
|
2078
2143
|
const title = sessionLabelOf(s)
|
|
2079
2144
|
return `<button class="ds-session-item ${state.current === s.sessionId ? 'current' : ''}" data-id="${esc(s.sessionId)}">
|
|
2080
|
-
<span class="ds-session-title">${esc(title)}</span>
|
|
2145
|
+
<span class="ds-session-title">${pinnedSet.has(s.sessionId) ? '<span class="ds-session-pin" aria-label="' + esc(t('ds.pinnedSession')) + '">📌</span> ' : ''}${esc(title)}</span>
|
|
2081
2146
|
<span class="ds-session-workspace" title="${esc(workspace)}">⌂ ${esc(workspaceName)}</span>
|
|
2082
2147
|
<span class="ds-session-meta"><span class="ds-session-dot ${s.running ? 'running' : ''}"></span>${fmtTime(sessionSortTime(s))}</span>
|
|
2083
2148
|
</button>`
|
|
@@ -2161,6 +2226,8 @@ async function openSession(id) {
|
|
|
2161
2226
|
if (state.current && state.current !== id) void archiveEmptySessionOnLeave(state.current,true)
|
|
2162
2227
|
cancelHistoryLoad()
|
|
2163
2228
|
state.current = id
|
|
2229
|
+
if (typeof syncComposerToolsScope === 'function') syncComposerToolsScope()
|
|
2230
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.setSession?.(id)
|
|
2164
2231
|
setSessionRecovery('loading')
|
|
2165
2232
|
state.history = emptyDesktopHistory()
|
|
2166
2233
|
const openingHistory=state.history, openingConnection=captureConnection()
|
|
@@ -2174,6 +2241,7 @@ async function openSession(id) {
|
|
|
2174
2241
|
renderSessionCards()
|
|
2175
2242
|
renderQueue()
|
|
2176
2243
|
renderSessionPendingDesktop()
|
|
2244
|
+
if (typeof hostQueue !== 'undefined') hostQueue?.reconnect()
|
|
2177
2245
|
updateComposerStatus()
|
|
2178
2246
|
void refreshCompactionStatus(id)
|
|
2179
2247
|
try { const restored=await restoreCachedHistory();globalThis.DshDiagnostics?.record('history.cache',{phase:restored?'hit':'miss',sessionId:id}) } catch(error) {
|
|
@@ -2198,6 +2266,10 @@ async function closeSession() {
|
|
|
2198
2266
|
cancelHistoryLoad()
|
|
2199
2267
|
const cleanup=sessionId&&!wasLoading&&state.history.loaded&&!state.history.loading&&!state.history.renderError
|
|
2200
2268
|
state.current = null
|
|
2269
|
+
if (typeof syncComposerToolsScope === 'function') syncComposerToolsScope()
|
|
2270
|
+
if (typeof planReviewController !== 'undefined') planReviewController?.setSession?.(null)
|
|
2271
|
+
if (typeof turnDiffController !== 'undefined') turnDiffController?.setSession?.(null)
|
|
2272
|
+
if (typeof planReviewHost !== 'undefined') planReviewHost?.classList.add('hidden')
|
|
2201
2273
|
setSessionRecovery('idle')
|
|
2202
2274
|
state.history = emptyDesktopHistory()
|
|
2203
2275
|
showView('view-sessions')
|
|
@@ -2211,9 +2283,49 @@ async function closeSession() {
|
|
|
2211
2283
|
if(cleanup)await archiveEmptySessionOnLeave(sessionId,true)
|
|
2212
2284
|
}
|
|
2213
2285
|
|
|
2286
|
+
function readSessionCache() {
|
|
2287
|
+
const scope = historyCacheScope()
|
|
2288
|
+
if (globalThis.DshSessionCache?.read) return globalThis.DshSessionCache.read(scope)
|
|
2289
|
+
try { const items = JSON.parse(LS.get(scope + ':sessions', '')); return Array.isArray(items) ? items : null } catch { return null }
|
|
2290
|
+
}
|
|
2291
|
+
function writeSessionCache(list) {
|
|
2292
|
+
const scope = historyCacheScope()
|
|
2293
|
+
const value = Array.isArray(list) ? list.slice(0, 80) : []
|
|
2294
|
+
if (globalThis.DshSessionCache?.write) return globalThis.DshSessionCache.write(scope, value)
|
|
2295
|
+
const canonical = scope.replace(/^historyCacheV2:/, 'sessionsCacheV2:')
|
|
2296
|
+
try {
|
|
2297
|
+
LS.set(canonical, JSON.stringify(value))
|
|
2298
|
+
if (LS.get(scope + ':sessions', null) !== null) LS.set(scope + ':sessions', JSON.stringify(value))
|
|
2299
|
+
return true
|
|
2300
|
+
} catch { return false }
|
|
2301
|
+
}
|
|
2302
|
+
function clearSessionCache(scope = historyCacheScope()) {
|
|
2303
|
+
if (globalThis.DshSessionCache?.clear) return globalThis.DshSessionCache.clear(scope)
|
|
2304
|
+
try { LS.del(scope.replace(/^historyCacheV2:/, 'sessionsCacheV2:')) } catch {}
|
|
2305
|
+
try { LS.del(scope + ':sessions') } catch {}
|
|
2306
|
+
}
|
|
2307
|
+
function clearAllSessionCaches() {
|
|
2308
|
+
if (globalThis.DshSessionCache?.clearAll) return globalThis.DshSessionCache.clearAll()
|
|
2309
|
+
try {
|
|
2310
|
+
const storage = globalThis.localStorage
|
|
2311
|
+
if (!storage) return false
|
|
2312
|
+
for (const key of Object.keys(storage)) {
|
|
2313
|
+
if (key.startsWith('sessionsCacheV2:') || (key.startsWith('historyCacheV2:') && key.endsWith(':sessions'))) storage.removeItem(key)
|
|
2314
|
+
}
|
|
2315
|
+
return true
|
|
2316
|
+
} catch { return false }
|
|
2317
|
+
}
|
|
2318
|
+
|
|
2214
2319
|
function restoreCachedSessionList() {
|
|
2215
2320
|
if(state.sessions.length)return
|
|
2216
|
-
try
|
|
2321
|
+
try {
|
|
2322
|
+
const items = readSessionCache()
|
|
2323
|
+
state.sessions = Array.isArray(items) ? items.filter(item => typeof item?.sessionId === 'string').slice(0, 80) : []
|
|
2324
|
+
state.byId = new Map(state.sessions.map(item => [item.sessionId, item]))
|
|
2325
|
+
// Render even when no cache exists: an identity switch must clear the old
|
|
2326
|
+
// connection's list instead of leaving its DOM behind.
|
|
2327
|
+
renderSessions()
|
|
2328
|
+
} catch {}
|
|
2217
2329
|
}
|
|
2218
2330
|
|
|
2219
2331
|
let conversationView = null
|
|
@@ -2245,7 +2357,7 @@ function scheduleHistoryCacheSave() {
|
|
|
2245
2357
|
}
|
|
2246
2358
|
async function saveHistoryCache(scope=historyCacheScope(),id=state.current,history=state.history) {
|
|
2247
2359
|
if(!id||!history.visible.length||history.tailEvicted)return
|
|
2248
|
-
const saved=await window.DshHistory.cacheSave(scope,id,{title:titleOf(state.byId.get(id)),events:history.visible
|
|
2360
|
+
const saved=await window.DshHistory.cacheSave(scope,id,{title:titleOf(state.byId.get(id)),events:history.visible,minSeq:history.minSeq,hasMore:history.hasMore,partialReasoning:[...history.partialReasoning.values()]},250)
|
|
2249
2361
|
if(!saved&&state.current===id&&state.history===history&&scope===historyCacheScope())historySource('saveFailed')
|
|
2250
2362
|
if(saved&&state.current===id&&state.history===history&&scope===historyCacheScope()&&['synced','saveFailed'].includes(history.source))historySource('saved')
|
|
2251
2363
|
}
|
|
@@ -2359,7 +2471,8 @@ const INTERESTING_EVENTS = new Set([
|
|
|
2359
2471
|
'agent/status', 'checkpoint/created', 'compaction/complete', 'compaction/summary',
|
|
2360
2472
|
'goal/created', 'goal/updated', 'goal/completed', 'goal/cleared',
|
|
2361
2473
|
'todo/updated', 'plan/updated', 'question/asked', 'question/resolved',
|
|
2362
|
-
'approval/asked', 'approval/resolved'
|
|
2474
|
+
'approval/asked', 'approval/resolved',
|
|
2475
|
+
'deliverables/presented', 'workspace/changes'
|
|
2363
2476
|
])
|
|
2364
2477
|
function messageSource(data) {
|
|
2365
2478
|
const source = data?.source ?? data?.message?.source
|
|
@@ -2471,9 +2584,11 @@ function eventHtml(entry) {
|
|
|
2471
2584
|
const ev = entry.event || {}
|
|
2472
2585
|
const data = ev.data || {}
|
|
2473
2586
|
const type = ev.type || 'event'
|
|
2474
|
-
const failure = window.DshActivity?.failureHtml?.(window.DshActivity.failure(ev)) || ''
|
|
2587
|
+
const failure = window.DshActivity?.failureHtml?.(window.DshActivity.failure(ev), false, entry.view?.continuation) || ''
|
|
2475
2588
|
if (entry.view?.turnResult) return failure + window.DshTurnResults.html(entry.view.turnResult)
|
|
2476
|
-
if (type === 'turn/start'
|
|
2589
|
+
if (type === 'turn/start') return failure
|
|
2590
|
+
if (type === 'turn/end') return failure + (entry.view?.turnDiffHtml || '')
|
|
2591
|
+
if (type === 'deliverables/presented' || type === 'workspace/changes') return ''
|
|
2477
2592
|
if (type === 'assistant/attempt') return window.DshActivity?.attemptHtml?.(ev) || ''
|
|
2478
2593
|
if (entry.view?.activityTurn) return window.DshActivity.turnHtml(entry.view.activityTurn)
|
|
2479
2594
|
if (entry.view?.activityGroup) return window.DshActivity.groupHtml(entry.view.activityGroup, eventHtml)
|
|
@@ -2491,7 +2606,7 @@ function eventHtml(entry) {
|
|
|
2491
2606
|
if (type === 'user/message' && !isHumanUserMessage(ev)) return ''
|
|
2492
2607
|
const text = blocks.map((block,index)=>blockHtml(block,index,{...data,seq:entry.seq,suppressBlockTools:state.history.suppressBlockTools})).join('')
|
|
2493
2608
|
if (!text) return ''
|
|
2494
|
-
return `<div class="ds-msg ${esc(role)}"><div class="role">${esc(role === 'user' ? t('ds.role.me') : t('ds.role.dsh'))}</div>${text}</div>`
|
|
2609
|
+
return `<div class="ds-msg ${esc(role)}" data-seq="${esc(entry.seq)}"><div class="role">${esc(role === 'user' ? t('ds.role.me') : t('ds.role.dsh'))}</div>${text}</div>`
|
|
2495
2610
|
}
|
|
2496
2611
|
if (type === 'tool/call') {
|
|
2497
2612
|
const name = data.name || data.toolName || t('ds.toolDefault')
|
|
@@ -2535,6 +2650,7 @@ function bindTurnResultActions() {
|
|
|
2535
2650
|
if (!state.byId.has(id)) {
|
|
2536
2651
|
const branch = { ...parent, projections: parent?.projections ? { ...JSON.parse(JSON.stringify(parent.projections)), asOfSeq: 0 } : undefined,
|
|
2537
2652
|
sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
|
|
2653
|
+
if (branch.projections?.values) delete branch.projections.values.conversationContinuation
|
|
2538
2654
|
state.byId.set(id, branch)
|
|
2539
2655
|
state.sessions.unshift(branch)
|
|
2540
2656
|
renderSessions()
|
|
@@ -2559,12 +2675,36 @@ function renderHistory(reset=false, mode='auto') {
|
|
|
2559
2675
|
prepared = window.DshTurnResults.decorate(prepared, state.history.visible, { sessionId: state.current, canFork: canForkTurnResult() })
|
|
2560
2676
|
bindTurnResultActions()
|
|
2561
2677
|
}
|
|
2678
|
+
if (typeof turnDiffController !== 'undefined' && turnDiffController) {
|
|
2679
|
+
turnDiffController.setLayout('desktop')
|
|
2680
|
+
turnDiffController.setSession(state.current)
|
|
2681
|
+
if (typeof turnDiffHtmlFor === 'function') prepared = prepared.map(entry => ({ ...entry, view: { ...entry.view, turnDiffHtml: turnDiffHtmlFor(entry) } }))
|
|
2682
|
+
}
|
|
2683
|
+
if (activity?.withContinuation && activeGatewayCapability('sessionContinuation') === true) {
|
|
2684
|
+
const sessionId = state.current, history = state.history, connection = captureConnection()
|
|
2685
|
+
const session = state.byId.get(sessionId)
|
|
2686
|
+
prepared = activity.withContinuation($('history'), prepared, {
|
|
2687
|
+
history, ending: session && session.origin !== 'subagent' && session.formatStatus !== 'migration-required'
|
|
2688
|
+
&& !(state.archivedIds || []).includes(sessionId)
|
|
2689
|
+
? proj(session, 'conversationContinuation') : undefined,
|
|
2690
|
+
valid: () => connection.valid() && state.current === sessionId && state.history === history,
|
|
2691
|
+
render: () => renderHistory(),
|
|
2692
|
+
submit: ending => rpc('session.continue', { sessionId, ending }),
|
|
2693
|
+
failed: error => {
|
|
2694
|
+
if (error.operationPending) notifyPendingOperation(error, connection)
|
|
2695
|
+
else if (connection.valid() && state.current === sessionId && state.history === history) {
|
|
2696
|
+
toast(error.message, 'err'); void resyncCurrentSession()
|
|
2697
|
+
}
|
|
2698
|
+
},
|
|
2699
|
+
})
|
|
2700
|
+
}
|
|
2562
2701
|
if(window.DshActivity?.groupFailures)prepared=window.DshActivity.groupFailures(prepared)
|
|
2563
2702
|
const hostError = state.runtimeErrors?.get(state.current)
|
|
2564
2703
|
const recordedError = state.history.visible.some(entry => window.DshActivity?.failure?.(entry.event)?.message === hostError)
|
|
2565
2704
|
const runtimeHtml = hostError && !recordedError ? window.DshActivity?.failureHtml?.(hostError) || '' : ''
|
|
2566
2705
|
getConversationView().set(prepared,{reset,follow:mode==='bottom',live:(groupLive?'':partialReasoningHtml())+runtimeHtml,hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('ds.historyEmpty')})
|
|
2567
2706
|
window.DshImagePreview?.hydrate?.($('history'))
|
|
2707
|
+
if (typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
2568
2708
|
}
|
|
2569
2709
|
window.applyStreamPreference=()=>{if(state.current)renderHistory(false,'auto')}
|
|
2570
2710
|
|
|
@@ -2825,7 +2965,10 @@ async function sendMessage(requestedMode = 'queue') {
|
|
|
2825
2965
|
if (typeof window !== 'undefined') window.DshSlashSuggestions?.close()
|
|
2826
2966
|
if (state.byId.get(state.current)?.origin === 'subagent') { toast('子代理记录为只读 / Subagent records are read only'); return false }
|
|
2827
2967
|
const input = $('composer')
|
|
2828
|
-
const originalText = input.value,
|
|
2968
|
+
const originalText = input.value, clean = originalText.trim()
|
|
2969
|
+
const quoted = clean && !clean.startsWith('/') && typeof composerTools !== 'undefined' ? composerTools?.quotes() || [] : []
|
|
2970
|
+
const quoteText = quoted.length ? window.DshComposerTools.formatQuotes(quoted) : ''
|
|
2971
|
+
const text = [quoteText, clean].filter(Boolean).join('\n\n')
|
|
2829
2972
|
if (!text || !state.current) return
|
|
2830
2973
|
const sessionId = state.current, connection = captureConnection(), history = state.history
|
|
2831
2974
|
const pending = sendMessage.pending ||= new Set()
|
|
@@ -2834,7 +2977,7 @@ async function sendMessage(requestedMode = 'queue') {
|
|
|
2834
2977
|
const valid = () => connection.valid() && state.current === sessionId && state.history === history
|
|
2835
2978
|
try {
|
|
2836
2979
|
state.sessionActivity.add(sessionId)
|
|
2837
|
-
if (await runSlashCommand(
|
|
2980
|
+
if (await runSlashCommand(clean)) { if (valid() && input.value === originalText) input.value = ''; return }
|
|
2838
2981
|
if (!valid()) return
|
|
2839
2982
|
setSessionRecovery('resuming')
|
|
2840
2983
|
const v = await safeRpc('session.prompt', {
|
|
@@ -2845,6 +2988,7 @@ async function sendMessage(requestedMode = 'queue') {
|
|
|
2845
2988
|
if (!valid()) return
|
|
2846
2989
|
if (v?.accepted) {
|
|
2847
2990
|
if (input.value === originalText) input.value = ''
|
|
2991
|
+
if (quoted.length) composerTools?.clearQuotes(quoted.map(quote => quote.id))
|
|
2848
2992
|
setSessionRecovery('ready'); noteSessionTurnTime(sessionId, Date.now()); renderSessions(); toast(t('ds.toastSent'), 'ok')
|
|
2849
2993
|
}
|
|
2850
2994
|
else setSessionRecovery('error')
|
|
@@ -2923,43 +3067,28 @@ function updateComposerStatus() {
|
|
|
2923
3067
|
: t('ds.composerRunning')
|
|
2924
3068
|
updateSessionActions()
|
|
2925
3069
|
}
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
if (
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
}
|
|
2947
|
-
}
|
|
3070
|
+
const hostAccess = connection => window.DshHostQueue.readAccess(connection, apiUrl)
|
|
3071
|
+
const hostQueue = window.DshHostQueue?.create({ rpc, access: hostAccess, capture: captureConnection, box: () => $('queue-dock'),
|
|
3072
|
+
session: () => state.current, items: () => state.queues[state.current], running: () => !!state.byId.get(state.current)?.running,
|
|
3073
|
+
apply(sessionId, snapshot) {
|
|
3074
|
+
state.queues[sessionId] = snapshot.items
|
|
3075
|
+
const session = state.byId.get(sessionId)
|
|
3076
|
+
if (session) session.running = snapshot.running
|
|
3077
|
+
},
|
|
3078
|
+
})
|
|
3079
|
+
const hostSchedule = window.DshHostSchedule?.create({ rpc, access: hostAccess, capture: captureConnection, box: () => $('view-schedule'),
|
|
3080
|
+
workspaces: workspaceItems,
|
|
3081
|
+
sessions: () => state.sessions.filter(row => row.origin !== 'subagent' && !state.archivedIds.includes(row.sessionId)).map(row => ({ id: row.sessionId, label: titleOf(row) })),
|
|
3082
|
+
async openSession(id) {
|
|
3083
|
+
const connection = captureConnection()
|
|
3084
|
+
await refreshSessions()
|
|
3085
|
+
if (!connection.valid()) return
|
|
3086
|
+
if (!state.byId.has(id)) return toast(t('ds.sessionUntitled'), 'err')
|
|
3087
|
+
await openSession(id)
|
|
3088
|
+
},
|
|
3089
|
+
})
|
|
2948
3090
|
function renderQueue() {
|
|
2949
|
-
|
|
2950
|
-
if (!box) return
|
|
2951
|
-
const sessionId = state.current
|
|
2952
|
-
const s = state.byId.get(sessionId)
|
|
2953
|
-
const items = (state.queues[sessionId] || []).filter(item => item?.placement === 'queued')
|
|
2954
|
-
box.classList.toggle('hidden', !items.length)
|
|
2955
|
-
box.innerHTML = items.length ? `<div class="ds-queue-dock-head"><span>⌁</span><span>${esc(t('queue.title'))} · ${items.length}</span></div><div class="ds-queue-dock-list">${items.map(item => {
|
|
2956
|
-
const key = `${sessionId}:${item.id}`
|
|
2957
|
-
const busy = !!state.queueSteering[key]
|
|
2958
|
-
return `<div class="ds-queue-dock-item"><span class="ds-queue-dock-preview" title="${esc(queuePreview(item))}">${esc(queuePreview(item))}</span><button type="button" class="ds-mini-btn ds-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>`
|
|
2959
|
-
}).join('')}</div>` : ''
|
|
2960
|
-
box.querySelectorAll('[data-queue-steer]').forEach(button => {
|
|
2961
|
-
button.addEventListener('click', () => steerQueueItem(button.dataset.queueSteer))
|
|
2962
|
-
})
|
|
3091
|
+
hostQueue?.render()
|
|
2963
3092
|
updateComposerStatus()
|
|
2964
3093
|
}
|
|
2965
3094
|
|
|
@@ -3136,6 +3265,11 @@ function questionMarkup(item) {
|
|
|
3136
3265
|
|
|
3137
3266
|
function openQuestionModal(q) {
|
|
3138
3267
|
if (!q) return
|
|
3268
|
+
if (typeof isPlanReviewQuestion === 'function' && isPlanReviewQuestion(q)) {
|
|
3269
|
+
if (typeof refreshPlanReview === 'function') refreshPlanReview()
|
|
3270
|
+
if (typeof planReviewHost !== 'undefined') planReviewHost?.scrollIntoView?.({ behavior: 'smooth', block: 'center' })
|
|
3271
|
+
return
|
|
3272
|
+
}
|
|
3139
3273
|
state.questionModal = q
|
|
3140
3274
|
$('question-body').innerHTML = q.questions.map((item, i) => `
|
|
3141
3275
|
<div class="ds-q-item">
|
|
@@ -3178,6 +3312,493 @@ async function submitQuestion() {
|
|
|
3178
3312
|
} else toast(t('ds.stale'), 'err')
|
|
3179
3313
|
}
|
|
3180
3314
|
|
|
3315
|
+
/* ---------------- B/C 输入、搜索与管理 ---------------- */
|
|
3316
|
+
let composerTools = null
|
|
3317
|
+
let sessionSearchController = null
|
|
3318
|
+
let sessionSearchMount = null
|
|
3319
|
+
let sessionManager = null
|
|
3320
|
+
let workspaceAdminMount = null
|
|
3321
|
+
let quoteSelectionButton = null
|
|
3322
|
+
let planReviewController = null
|
|
3323
|
+
let planReviewHost = null
|
|
3324
|
+
let turnDiffController = null
|
|
3325
|
+
let turnDiffRoot = null
|
|
3326
|
+
|
|
3327
|
+
function bcEnglish() { return I18N.lang === 'en' }
|
|
3328
|
+
function bcText(zh, en) { return bcEnglish() ? en : zh }
|
|
3329
|
+
|
|
3330
|
+
async function bcRpc(method, payload, options = {}) {
|
|
3331
|
+
return rpc(method, payload, Number.isFinite(options.timeoutMs) ? options.timeoutMs : 45000, options.signal || null)
|
|
3332
|
+
}
|
|
3333
|
+
|
|
3334
|
+
function composerToolsHost() {
|
|
3335
|
+
return {
|
|
3336
|
+
scope: () => ({ key: JSON.stringify([connectionGeneration, state.current]), sessionId: state.current || '', connection: captureConnection() }),
|
|
3337
|
+
async listReferences(scope, query) {
|
|
3338
|
+
const sessionId = scope?.sessionId || state.current
|
|
3339
|
+
if (!sessionId) return null
|
|
3340
|
+
const [files, sessions] = await Promise.allSettled([
|
|
3341
|
+
bcRpc('fileReferences.list', { sessionId, query: String(query || '') }, { timeoutMs: 12000 }),
|
|
3342
|
+
bcRpc('sessionReferenceResolver.candidates', { sessionId, query: String(query || '') }, { timeoutMs: 12000 }),
|
|
3343
|
+
])
|
|
3344
|
+
if (files.status !== 'fulfilled' && sessions.status !== 'fulfilled') return null
|
|
3345
|
+
const references = []
|
|
3346
|
+
if (files.status === 'fulfilled' && Array.isArray(files.value)) {
|
|
3347
|
+
for (const row of files.value) {
|
|
3348
|
+
const insert = window.DshComposerTools.fileReferenceMention(row)
|
|
3349
|
+
if (!insert) continue
|
|
3350
|
+
references.push({
|
|
3351
|
+
insert,
|
|
3352
|
+
label: row?.kind === 'directory' ? String(row?.path || '') + '/' : String(row?.path || ''),
|
|
3353
|
+
detail: row?.kind === 'directory' ? bcText('目录', 'Directory') : bcText('文件', 'File'),
|
|
3354
|
+
kind: 'file',
|
|
3355
|
+
allowed: true,
|
|
3356
|
+
})
|
|
3357
|
+
}
|
|
3358
|
+
}
|
|
3359
|
+
if (sessions.status === 'fulfilled' && Array.isArray(sessions.value)) {
|
|
3360
|
+
for (const row of sessions.value) {
|
|
3361
|
+
if (typeof row?.mention !== 'string' || !row.mention.startsWith('@')) continue
|
|
3362
|
+
references.push({
|
|
3363
|
+
insert: row.mention,
|
|
3364
|
+
label: row.displayTitle || row.label || row.sessionId || '',
|
|
3365
|
+
detail: row.cwd || '',
|
|
3366
|
+
kind: 'session',
|
|
3367
|
+
allowed: true,
|
|
3368
|
+
})
|
|
3369
|
+
}
|
|
3370
|
+
}
|
|
3371
|
+
return { supported: true, references }
|
|
3372
|
+
},
|
|
3373
|
+
notice: (text, kind) => toast(text, kind === 'err' ? 'err' : ''),
|
|
3374
|
+
}
|
|
3375
|
+
}
|
|
3376
|
+
|
|
3377
|
+
function selectedMessageQuote() {
|
|
3378
|
+
const selection = window.getSelection?.()
|
|
3379
|
+
if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null
|
|
3380
|
+
const range = selection.getRangeAt(0)
|
|
3381
|
+
const history = $('history')
|
|
3382
|
+
if (!history || !range.commonAncestorContainer) return null
|
|
3383
|
+
const startNode = range.startContainer.nodeType === 3 ? range.startContainer.parentElement : range.startContainer
|
|
3384
|
+
const endNode = range.endContainer.nodeType === 3 ? range.endContainer.parentElement : range.endContainer
|
|
3385
|
+
const startMessage = startNode?.closest?.('.ds-msg')
|
|
3386
|
+
const endMessage = endNode?.closest?.('.ds-msg')
|
|
3387
|
+
if (!startMessage || !endMessage || startMessage !== endMessage || !history.contains(startMessage)) return null
|
|
3388
|
+
const text = selection.toString().replace(/\r\n?/g, '\n').trim()
|
|
3389
|
+
if (!text) return null
|
|
3390
|
+
const role = startMessage.classList.contains('user') ? 'user' : startMessage.classList.contains('assistant') ? 'assistant' : ''
|
|
3391
|
+
return { text, role, messageId: startMessage.dataset.seq || '', rect: range.getBoundingClientRect() }
|
|
3392
|
+
}
|
|
3393
|
+
|
|
3394
|
+
function hideQuoteSelectionButton() {
|
|
3395
|
+
if (!quoteSelectionButton) return
|
|
3396
|
+
quoteSelectionButton.hidden = true
|
|
3397
|
+
quoteSelectionButton.classList.add('hidden')
|
|
3398
|
+
}
|
|
3399
|
+
|
|
3400
|
+
function updateQuoteSelectionButton() {
|
|
3401
|
+
if (!quoteSelectionButton || !composerTools) return
|
|
3402
|
+
const selected = selectedMessageQuote()
|
|
3403
|
+
if (!selected) { hideQuoteSelectionButton(); return }
|
|
3404
|
+
const rect = selected.rect
|
|
3405
|
+
quoteSelectionButton.style.left = Math.max(8, Math.min(window.innerWidth - 150, rect.left + rect.width / 2 - 70)) + 'px'
|
|
3406
|
+
quoteSelectionButton.style.top = Math.max(8, Math.min(window.innerHeight - 56, rect.bottom + 8)) + 'px'
|
|
3407
|
+
quoteSelectionButton.hidden = false
|
|
3408
|
+
quoteSelectionButton.classList.remove('hidden')
|
|
3409
|
+
}
|
|
3410
|
+
|
|
3411
|
+
function initQuoteSelection() {
|
|
3412
|
+
if (quoteSelectionButton) return
|
|
3413
|
+
quoteSelectionButton = document.createElement('button')
|
|
3414
|
+
quoteSelectionButton.type = 'button'
|
|
3415
|
+
quoteSelectionButton.className = 'ct-quote-pick hidden'
|
|
3416
|
+
quoteSelectionButton.hidden = true
|
|
3417
|
+
quoteSelectionButton.textContent = t('ds.quoteSelection')
|
|
3418
|
+
quoteSelectionButton.addEventListener('pointerdown', event => event.preventDefault())
|
|
3419
|
+
quoteSelectionButton.addEventListener('click', event => {
|
|
3420
|
+
event.preventDefault()
|
|
3421
|
+
const selected = selectedMessageQuote()
|
|
3422
|
+
hideQuoteSelectionButton()
|
|
3423
|
+
if (!selected || !composerTools) return
|
|
3424
|
+
composerTools.addQuote({ messageId: selected.messageId, role: selected.role, text: selected.text })
|
|
3425
|
+
window.getSelection?.()?.removeAllRanges?.()
|
|
3426
|
+
toast(t('ds.quoteAdded'), 'ok')
|
|
3427
|
+
})
|
|
3428
|
+
document.body.append(quoteSelectionButton)
|
|
3429
|
+
document.addEventListener('selectionchange', () => {
|
|
3430
|
+
if (document.activeElement === $('composer')) return
|
|
3431
|
+
updateQuoteSelectionButton()
|
|
3432
|
+
})
|
|
3433
|
+
window.addEventListener('scroll', hideQuoteSelectionButton, { passive: true })
|
|
3434
|
+
window.addEventListener('resize', hideQuoteSelectionButton)
|
|
3435
|
+
}
|
|
3436
|
+
|
|
3437
|
+
function initComposerToolsUi() {
|
|
3438
|
+
if (composerTools || !window.DshComposerTools) return
|
|
3439
|
+
const input = $('composer')
|
|
3440
|
+
if (!input) return
|
|
3441
|
+
const anchor = document.createElement('div')
|
|
3442
|
+
anchor.className = 'ct-anchor'
|
|
3443
|
+
const menu = document.createElement('div')
|
|
3444
|
+
menu.id = 'composer-tools-menu'
|
|
3445
|
+
menu.className = 'ct-menu hidden'
|
|
3446
|
+
menu.hidden = true
|
|
3447
|
+
anchor.append(menu)
|
|
3448
|
+
const quotes = document.createElement('div')
|
|
3449
|
+
quotes.id = 'composer-tools-quotes'
|
|
3450
|
+
quotes.className = 'ct-quotes hidden'
|
|
3451
|
+
quotes.hidden = true
|
|
3452
|
+
const hint = document.createElement('p')
|
|
3453
|
+
hint.id = 'composer-tools-hint'
|
|
3454
|
+
hint.className = 'ct-hint hidden'
|
|
3455
|
+
hint.hidden = true
|
|
3456
|
+
input.before(anchor)
|
|
3457
|
+
input.before(quotes)
|
|
3458
|
+
input.before(hint)
|
|
3459
|
+
composerTools = window.DshComposerTools.create({
|
|
3460
|
+
input,
|
|
3461
|
+
menu,
|
|
3462
|
+
hint,
|
|
3463
|
+
quoteList: quotes,
|
|
3464
|
+
host: composerToolsHost(),
|
|
3465
|
+
commands: false,
|
|
3466
|
+
onChange: () => window.DshWorkflow?.update(),
|
|
3467
|
+
})
|
|
3468
|
+
initQuoteSelection()
|
|
3469
|
+
}
|
|
3470
|
+
|
|
3471
|
+
function syncComposerToolsScope() {
|
|
3472
|
+
composerTools?.setScope?.({ key: JSON.stringify([connectionGeneration, state.current]), sessionId: state.current || '', connection: captureConnection() })
|
|
3473
|
+
}
|
|
3474
|
+
|
|
3475
|
+
function initSessionSearchUi() {
|
|
3476
|
+
if (sessionSearchController || !window.DshSessionSearch) return
|
|
3477
|
+
const sort = $('session-sort')
|
|
3478
|
+
const list = $('session-list')
|
|
3479
|
+
if (!sort || !list) return
|
|
3480
|
+
const toggle = document.createElement('button')
|
|
3481
|
+
toggle.id = 'btn-session-search'
|
|
3482
|
+
toggle.type = 'button'
|
|
3483
|
+
toggle.className = 'ds-icon-btn dr-bc-search-toggle'
|
|
3484
|
+
toggle.textContent = '⌕'
|
|
3485
|
+
toggle.title = t('ds.searchSessions')
|
|
3486
|
+
toggle.setAttribute('aria-label', t('ds.searchSessions'))
|
|
3487
|
+
toggle.setAttribute('aria-expanded', 'false')
|
|
3488
|
+
sort.before(toggle)
|
|
3489
|
+
const host = document.createElement('section')
|
|
3490
|
+
host.id = 'session-search-host'
|
|
3491
|
+
host.className = 'hidden'
|
|
3492
|
+
list.before(host)
|
|
3493
|
+
sessionSearchController = window.DshSessionSearch.init({
|
|
3494
|
+
rpc: bcRpc,
|
|
3495
|
+
sessions: () => (state.sessions || []).filter(s => s && s.sessionId && s.origin !== 'subagent' && s.blank !== true),
|
|
3496
|
+
workspaces: () => workspaceItems(),
|
|
3497
|
+
archivedSessionIds: () => state.archivedIds || [],
|
|
3498
|
+
pinnedSessionIds: () => state.pinnedIds || [],
|
|
3499
|
+
titleOf: session => titleOf(session),
|
|
3500
|
+
historyRoot: () => $('history'),
|
|
3501
|
+
openSession: async (sessionId) => { toggleSessionSearch(false); await openSession(sessionId) },
|
|
3502
|
+
notice: message => toast(message),
|
|
3503
|
+
})
|
|
3504
|
+
sessionSearchMount = window.DshSessionSearch.mount(host, sessionSearchController, {
|
|
3505
|
+
onOpen: result => { if (result?.opened) toggleSessionSearch(false) },
|
|
3506
|
+
})
|
|
3507
|
+
toggle.addEventListener('click', () => toggleSessionSearch())
|
|
3508
|
+
updateBcControlLabels()
|
|
3509
|
+
}
|
|
3510
|
+
|
|
3511
|
+
function toggleSessionSearch(force) {
|
|
3512
|
+
const host = $('session-search-host')
|
|
3513
|
+
const button = $('btn-session-search')
|
|
3514
|
+
if (!host || !button || !sessionSearchController) return
|
|
3515
|
+
const open = typeof force === 'boolean' ? force : host.classList.contains('hidden')
|
|
3516
|
+
host.classList.toggle('hidden', !open)
|
|
3517
|
+
button.classList.toggle('is-active', open)
|
|
3518
|
+
button.setAttribute('aria-expanded', String(open))
|
|
3519
|
+
if (open) {
|
|
3520
|
+
sessionSearchController.syncCatalog()
|
|
3521
|
+
sessionSearchMount?.refresh()
|
|
3522
|
+
requestAnimationFrame(() => host.querySelector('[data-dr-search-input]')?.focus())
|
|
3523
|
+
} else hideQuoteSelectionButton()
|
|
3524
|
+
}
|
|
3525
|
+
|
|
3526
|
+
function workspaceRemovalConfirmation(request) {
|
|
3527
|
+
const impact = request?.impact || {}
|
|
3528
|
+
return window.confirm([
|
|
3529
|
+
bcText(`移除工作区登记「${request?.displayTitle || impact.name || ''}」?`, `Remove the workspace registration "${request?.displayTitle || impact.name || ''}"?`),
|
|
3530
|
+
bcText('只删除工作区登记,不删除磁盘目录、文件或会话历史。', 'Only the Workspace registration is removed; directories, files and conversation history stay on disk.'),
|
|
3531
|
+
bcText(`该工作区关联 ${impact.total || 0} 个会话。移除后不再按该工作区分组。`, `${impact.total || 0} conversation(s) are associated. Their Workspace grouping disappears after removal.`),
|
|
3532
|
+
].join('\n\n'))
|
|
3533
|
+
}
|
|
3534
|
+
|
|
3535
|
+
function promptWorkspaceTitle({ workspace, current }) {
|
|
3536
|
+
const value = window.prompt(t('ds.workspaceRenamePrompt'), current || workspace?.title || '')
|
|
3537
|
+
return value == null ? null : String(value)
|
|
3538
|
+
}
|
|
3539
|
+
|
|
3540
|
+
function initSessionManagementUi() {
|
|
3541
|
+
if (sessionManager || !window.DshSessionManagement) return
|
|
3542
|
+
sessionManager = window.DshSessionManagement.init({
|
|
3543
|
+
rpc: bcRpc,
|
|
3544
|
+
sessions: () => state.sessions,
|
|
3545
|
+
workspaces: () => workspaceItems(),
|
|
3546
|
+
archivedSessionIds: () => state.archivedIds || [],
|
|
3547
|
+
pinnedSessionIds: () => state.pinnedIds || [],
|
|
3548
|
+
titleOf: session => titleOf(session),
|
|
3549
|
+
refresh: async () => { await Promise.all([refreshWorkbench({ silent: true }), refreshSessions()]) },
|
|
3550
|
+
confirm: workspaceRemovalConfirmation,
|
|
3551
|
+
promptTitle: promptWorkspaceTitle,
|
|
3552
|
+
toast,
|
|
3553
|
+
})
|
|
3554
|
+
const create = $('btn-new-workspace')
|
|
3555
|
+
const manageButton = document.createElement('button')
|
|
3556
|
+
manageButton.id = 'btn-manage-workspaces'
|
|
3557
|
+
manageButton.type = 'button'
|
|
3558
|
+
manageButton.className = 'ds-icon-btn'
|
|
3559
|
+
manageButton.textContent = '⚙'
|
|
3560
|
+
manageButton.title = t('ds.manageWorkspaces')
|
|
3561
|
+
manageButton.setAttribute('aria-label', t('ds.manageWorkspaces'))
|
|
3562
|
+
create?.before(manageButton)
|
|
3563
|
+
manageButton.addEventListener('click', openWorkspaceAdmin)
|
|
3564
|
+
const dialog = $('session-actions')
|
|
3565
|
+
if (dialog) {
|
|
3566
|
+
const box = document.createElement('div')
|
|
3567
|
+
box.id = 'session-admin-actions'
|
|
3568
|
+
dialog.querySelector('#btn-archive-session')?.before(box)
|
|
3569
|
+
window.DshSessionManagement.bindWorkspaceAdmin(box, sessionManager, {
|
|
3570
|
+
onResult: result => { if (result?.ok) renderSessions() },
|
|
3571
|
+
})
|
|
3572
|
+
}
|
|
3573
|
+
updateBcControlLabels()
|
|
3574
|
+
}
|
|
3575
|
+
|
|
3576
|
+
function ensureWorkspaceAdminModal() {
|
|
3577
|
+
let modal = $('modal-workspace-admin')
|
|
3578
|
+
if (modal) return modal
|
|
3579
|
+
modal = document.createElement('div')
|
|
3580
|
+
modal.id = 'modal-workspace-admin'
|
|
3581
|
+
modal.className = 'ds-modal hidden'
|
|
3582
|
+
modal.setAttribute('role', 'dialog')
|
|
3583
|
+
modal.setAttribute('aria-modal', 'true')
|
|
3584
|
+
modal.innerHTML = `<div class="ds-modal-card"><div class="ds-modal-title" id="workspace-admin-title"></div><div class="ds-modal-body" id="workspace-admin-host"></div><div class="ds-modal-actions"><button type="button" class="ds-btn" data-workspace-admin-close></button></div></div>`
|
|
3585
|
+
document.body.append(modal)
|
|
3586
|
+
modal.addEventListener('click', event => {
|
|
3587
|
+
if (event.target === modal || event.target.closest('[data-workspace-admin-close]')) modal.classList.add('hidden')
|
|
3588
|
+
})
|
|
3589
|
+
return modal
|
|
3590
|
+
}
|
|
3591
|
+
|
|
3592
|
+
function openWorkspaceAdmin() {
|
|
3593
|
+
if (!sessionManager) return
|
|
3594
|
+
const modal = ensureWorkspaceAdminModal()
|
|
3595
|
+
sessionManager.hydrate()
|
|
3596
|
+
if (!workspaceAdminMount) {
|
|
3597
|
+
workspaceAdminMount = window.DshSessionManagement.mountWorkspaceAdmin($('workspace-admin-host'), sessionManager, {
|
|
3598
|
+
promptTitle: promptWorkspaceTitle,
|
|
3599
|
+
onResult: result => { if (result?.ok) { renderSessions(); workspaceAdminMount?.refresh() } },
|
|
3600
|
+
})
|
|
3601
|
+
} else workspaceAdminMount.refresh()
|
|
3602
|
+
updateBcControlLabels()
|
|
3603
|
+
modal.classList.remove('hidden')
|
|
3604
|
+
}
|
|
3605
|
+
|
|
3606
|
+
function refreshSessionAdminActions() {
|
|
3607
|
+
const box = $('session-admin-actions')
|
|
3608
|
+
const session = state.byId.get(state.current)
|
|
3609
|
+
if (!box || !sessionManager || !session) return
|
|
3610
|
+
box.innerHTML = window.DshSessionManagement.renderSessionAdminActions(session, sessionManager.getState())
|
|
3611
|
+
}
|
|
3612
|
+
|
|
3613
|
+
function updateBcControlLabels() {
|
|
3614
|
+
const search = $('btn-session-search')
|
|
3615
|
+
if (search) { search.title = t('ds.searchSessions'); search.setAttribute('aria-label', t('ds.searchSessions')) }
|
|
3616
|
+
const manage = $('btn-manage-workspaces')
|
|
3617
|
+
if (manage) { manage.title = t('ds.manageWorkspaces'); manage.setAttribute('aria-label', t('ds.manageWorkspaces')) }
|
|
3618
|
+
if (quoteSelectionButton) quoteSelectionButton.textContent = t('ds.quoteSelection')
|
|
3619
|
+
const modal = $('modal-workspace-admin')
|
|
3620
|
+
if (modal) {
|
|
3621
|
+
modal.querySelector('#workspace-admin-title').textContent = t('ds.manageWorkspaces')
|
|
3622
|
+
modal.querySelector('[data-workspace-admin-close]').textContent = t('ds.close')
|
|
3623
|
+
}
|
|
3624
|
+
}
|
|
3625
|
+
|
|
3626
|
+
function initBcFeatures() {
|
|
3627
|
+
initComposerToolsUi()
|
|
3628
|
+
initSessionSearchUi()
|
|
3629
|
+
initSessionManagementUi()
|
|
3630
|
+
initReviewFeatures()
|
|
3631
|
+
syncComposerToolsScope()
|
|
3632
|
+
}
|
|
3633
|
+
|
|
3634
|
+
function isPlanReviewQuestion(question) {
|
|
3635
|
+
return !!window.DshPlanReview?.planReviewOf?.(question?.questions)
|
|
3636
|
+
}
|
|
3637
|
+
|
|
3638
|
+
function planReviewSnapshot(sessionId) {
|
|
3639
|
+
const session = state.byId.get(sessionId)
|
|
3640
|
+
const plan = session?.projections?.values?.plan
|
|
3641
|
+
return {
|
|
3642
|
+
plan,
|
|
3643
|
+
questions: (state.questions || []).filter(frame => String(frame?.sessionId || '') === String(sessionId || '')),
|
|
3644
|
+
connected: !!state.streamsOk?.mux,
|
|
3645
|
+
readOnly: false,
|
|
3646
|
+
capability: plan === undefined ? undefined : true,
|
|
3647
|
+
}
|
|
3648
|
+
}
|
|
3649
|
+
|
|
3650
|
+
function updatePlanReviewVisibility(view) {
|
|
3651
|
+
if (!planReviewHost) return
|
|
3652
|
+
const visible = !!(view?.plan?.supported || view?.review || (Array.isArray(view?.plans) && view.plans.length)
|
|
3653
|
+
|| (state.current && state.history.loaded))
|
|
3654
|
+
planReviewHost.classList.toggle('hidden', !visible)
|
|
3655
|
+
}
|
|
3656
|
+
|
|
3657
|
+
function refreshPlanReview() {
|
|
3658
|
+
if (!planReviewController) return
|
|
3659
|
+
let view = null
|
|
3660
|
+
try { view = planReviewController.render() } catch {}
|
|
3661
|
+
updatePlanReviewVisibility(view)
|
|
3662
|
+
return view
|
|
3663
|
+
}
|
|
3664
|
+
|
|
3665
|
+
function turnDiffEnabled() {
|
|
3666
|
+
return LS.get('turnDiffEnabled', '0') === '1'
|
|
3667
|
+
}
|
|
3668
|
+
|
|
3669
|
+
function turnDiffHtmlFor(entry) {
|
|
3670
|
+
if (!turnDiffController || !turnDiffController.isEnabled()) return ''
|
|
3671
|
+
if (entry?.event?.type !== 'turn/end') return ''
|
|
3672
|
+
const turnNumber = Number(entry.event?.data?.turn)
|
|
3673
|
+
if (!Number.isSafeInteger(turnNumber) || turnNumber < 1) return ''
|
|
3674
|
+
const full = turnDiffController.view()
|
|
3675
|
+
const turns = full.turns.filter(turn => turn.turn === turnNumber)
|
|
3676
|
+
if (!turns.length) return ''
|
|
3677
|
+
return `<div class="dr-diff-turn-slot" data-turn="${turnNumber}">${window.DshTurnDiff.viewHtml({ ...full, turns })}</div>`
|
|
3678
|
+
}
|
|
3679
|
+
|
|
3680
|
+
async function fetchHostChangesJson(path, query) {
|
|
3681
|
+
const url = new URL(apiUrl(path), location.href)
|
|
3682
|
+
for (const [key, value] of Object.entries(query || {})) url.searchParams.set(key, String(value))
|
|
3683
|
+
const res = await fetch(url.href, {
|
|
3684
|
+
headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
|
|
3685
|
+
cache: 'no-store',
|
|
3686
|
+
signal: AbortSignal.timeout(45000),
|
|
3687
|
+
})
|
|
3688
|
+
if (res.status === 401) toast(t('ds.toastAuth'), 'err')
|
|
3689
|
+
let data = null
|
|
3690
|
+
try { data = await res.json() } catch {}
|
|
3691
|
+
return { ok: res.ok, status: res.status, data }
|
|
3692
|
+
}
|
|
3693
|
+
|
|
3694
|
+
let turnDiffActionsBound = false
|
|
3695
|
+
function bindTurnDiffActions() {
|
|
3696
|
+
if (turnDiffActionsBound || !turnDiffController) return
|
|
3697
|
+
const container = $('history')
|
|
3698
|
+
if (!container) return
|
|
3699
|
+
turnDiffActionsBound = true
|
|
3700
|
+
container.addEventListener('click', event => {
|
|
3701
|
+
const button = event.target?.closest?.('[data-dr-diff-action]')
|
|
3702
|
+
if (!button || button.disabled) return
|
|
3703
|
+
const action = button.dataset?.drDiffAction || ''
|
|
3704
|
+
const turn = Number(button.dataset?.drDiffTurn)
|
|
3705
|
+
const index = Number(button.dataset?.drDiffFile)
|
|
3706
|
+
const delivery = Number(button.dataset?.drDiffDelivery)
|
|
3707
|
+
const run = {
|
|
3708
|
+
toggle: () => turnDiffController.toggleTurn(turn),
|
|
3709
|
+
file: () => turnDiffController.selectFile(turn, index),
|
|
3710
|
+
delivery: () => { turnDiffController.openDelivery(turn, delivery); return true },
|
|
3711
|
+
'retry-summary': () => turnDiffController.retrySummary(turn),
|
|
3712
|
+
'retry-diff': () => turnDiffController.retryDiff(turn, index),
|
|
3713
|
+
}[action]
|
|
3714
|
+
if (!run) return
|
|
3715
|
+
const finish = () => { if (state.current) renderHistory(false, 'keep') }
|
|
3716
|
+
try {
|
|
3717
|
+
const result = run()
|
|
3718
|
+
if (result && typeof result.then === 'function') result.then(finish, finish)
|
|
3719
|
+
else finish()
|
|
3720
|
+
} catch { finish() }
|
|
3721
|
+
})
|
|
3722
|
+
}
|
|
3723
|
+
|
|
3724
|
+
function initReviewFeatures() {
|
|
3725
|
+
if (window.DshPlanReview && !planReviewController) {
|
|
3726
|
+
const anchor = $('session-cards')
|
|
3727
|
+
if (anchor) {
|
|
3728
|
+
planReviewHost = document.createElement('section')
|
|
3729
|
+
planReviewHost.id = 'plan-review-host'
|
|
3730
|
+
planReviewHost.className = 'plan-review-host hidden'
|
|
3731
|
+
planReviewHost.setAttribute('aria-live', 'polite')
|
|
3732
|
+
anchor.after(planReviewHost)
|
|
3733
|
+
planReviewController = window.DshPlanReview.create({
|
|
3734
|
+
command: async line => ({ executed: await runSlashCommand(line, true) }),
|
|
3735
|
+
respond: (rpcId, value) => respond(rpcId, value),
|
|
3736
|
+
state: {
|
|
3737
|
+
sessionId: () => state.current,
|
|
3738
|
+
snapshot: sessionId => planReviewSnapshot(sessionId),
|
|
3739
|
+
entries: sessionId => state.current === sessionId ? state.history.visible : [],
|
|
3740
|
+
},
|
|
3741
|
+
dom: { root: planReviewHost },
|
|
3742
|
+
onOpenPlan: () => {},
|
|
3743
|
+
notify: (message, kind) => { if (message) toast(message, kind === 'err' ? 'err' : '') },
|
|
3744
|
+
})
|
|
3745
|
+
updatePlanReviewVisibility(planReviewController.view())
|
|
3746
|
+
}
|
|
3747
|
+
}
|
|
3748
|
+
if (window.DshTurnDiff && !turnDiffController) {
|
|
3749
|
+
turnDiffRoot = document.createElement('div')
|
|
3750
|
+
turnDiffRoot.hidden = true
|
|
3751
|
+
turnDiffController = window.DshTurnDiff.create({
|
|
3752
|
+
state: {
|
|
3753
|
+
sessionId: () => state.current,
|
|
3754
|
+
entries: sessionId => state.current === sessionId ? state.history.visible : [],
|
|
3755
|
+
},
|
|
3756
|
+
fetchJson: fetchHostChangesJson,
|
|
3757
|
+
dom: { root: turnDiffRoot },
|
|
3758
|
+
layout: 'desktop',
|
|
3759
|
+
enabled: turnDiffEnabled,
|
|
3760
|
+
onOpenFile: ({ path }) => {
|
|
3761
|
+
const name = String(path || '').split(/[\\/]/).pop() || ''
|
|
3762
|
+
if (path && name) openFsPreview(path, name)
|
|
3763
|
+
},
|
|
3764
|
+
notify: (message, kind) => { if (message) toast(message, kind === 'err' ? 'err' : '') },
|
|
3765
|
+
})
|
|
3766
|
+
turnDiffController.setEnabled(turnDiffEnabled())
|
|
3767
|
+
bindTurnDiffActions()
|
|
3768
|
+
}
|
|
3769
|
+
initTurnDiffSetting()
|
|
3770
|
+
}
|
|
3771
|
+
|
|
3772
|
+
function initTurnDiffSetting() {
|
|
3773
|
+
const page = $('settings-page-general')
|
|
3774
|
+
if (!page || $('opt-turn-diff')) return
|
|
3775
|
+
const group = page.querySelector('[data-workflow-settings-slot="input"]')
|
|
3776
|
+
|| page.querySelector('[data-workflow-settings-slot]')
|
|
3777
|
+
|| page
|
|
3778
|
+
const row = document.createElement('div')
|
|
3779
|
+
row.className = 'ds-setting-row'
|
|
3780
|
+
row.innerHTML = `<div><div class="ds-setting-name"></div><div class="ds-setting-desc"></div></div><label class="switch"><input type="checkbox" id="opt-turn-diff"><span class="slider"></span></label>`
|
|
3781
|
+
row.querySelector('.ds-setting-name').textContent = t('ds.turnDiffTitle')
|
|
3782
|
+
row.querySelector('.ds-setting-desc').textContent = t('ds.turnDiffDesc')
|
|
3783
|
+
group.append(row)
|
|
3784
|
+
const checkbox = row.querySelector('#opt-turn-diff')
|
|
3785
|
+
checkbox.checked = turnDiffEnabled()
|
|
3786
|
+
checkbox.addEventListener('change', () => {
|
|
3787
|
+
LS.set('turnDiffEnabled', checkbox.checked ? '1' : '0')
|
|
3788
|
+
turnDiffController?.setEnabled(checkbox.checked)
|
|
3789
|
+
if (state.current) renderHistory(false, 'keep')
|
|
3790
|
+
})
|
|
3791
|
+
}
|
|
3792
|
+
|
|
3793
|
+
function updateTurnDiffSettingLabel() {
|
|
3794
|
+
const row = $('opt-turn-diff')?.closest('.ds-setting-row')
|
|
3795
|
+
if (!row) return
|
|
3796
|
+
const name = row.querySelector('.ds-setting-name')
|
|
3797
|
+
const desc = row.querySelector('.ds-setting-desc')
|
|
3798
|
+
if (name) name.textContent = t('ds.turnDiffTitle')
|
|
3799
|
+
if (desc) desc.textContent = t('ds.turnDiffDesc')
|
|
3800
|
+
}
|
|
3801
|
+
|
|
3181
3802
|
/* ---------------- 文件传输 ---------------- */
|
|
3182
3803
|
function fsApiUrl(sub, params = {}) {
|
|
3183
3804
|
const u = new URL(apiUrl('/fs' + sub), location.href)
|
|
@@ -3205,6 +3826,11 @@ async function chatImageAttachment(attachment, sessionId) {
|
|
|
3205
3826
|
...(ref.height === undefined ? {} : { height: ref.height }),
|
|
3206
3827
|
...(ref.name ? { name: ref.name } : {}),
|
|
3207
3828
|
} }
|
|
3829
|
+
const session = state.byId?.get(sessionId)
|
|
3830
|
+
if (session?.origin === 'subagent' && session.parentSessionId) {
|
|
3831
|
+
payload.parentSessionId = session.parentSessionId
|
|
3832
|
+
payload.subagentMode = session.subagentMode || 'unknown'
|
|
3833
|
+
}
|
|
3208
3834
|
const result = await rpc('session.attachment', payload, 120000)
|
|
3209
3835
|
if (!connection.valid() || state.current !== sessionId) throw new Error('stale image')
|
|
3210
3836
|
return result
|
|
@@ -3510,7 +4136,9 @@ function orderedWorkspaceItems(items) {
|
|
|
3510
4136
|
}
|
|
3511
4137
|
function orderedWorkspaceSessions(workspaceId, items) {
|
|
3512
4138
|
const { value } = workbenchOrderScopeValue()
|
|
3513
|
-
|
|
4139
|
+
const pinned = new Set(state.pinnedIds || [])
|
|
4140
|
+
const ordered = orderedItems(items, value.sessionIds?.[String(workspaceId)], item => item.sessionId)
|
|
4141
|
+
return ordered.sort((a, b) => Number(pinned.has(b.sessionId)) - Number(pinned.has(a.sessionId)))
|
|
3514
4142
|
}
|
|
3515
4143
|
function saveWorkbenchOrder(mutator) {
|
|
3516
4144
|
const { store, value } = workbenchOrderScopeValue()
|
|
@@ -3552,6 +4180,7 @@ async function refreshWorkbench({ silent = false, discover = false } = {}) {
|
|
|
3552
4180
|
if (!valid()) return
|
|
3553
4181
|
if(wl){
|
|
3554
4182
|
state.archivedIds = Array.isArray(wl.archivedSessionIds) ? wl.archivedSessionIds : []
|
|
4183
|
+
state.pinnedIds = Array.isArray(wl.pinnedSessionIds) ? wl.pinnedSessionIds : []
|
|
3555
4184
|
state.workspaces = Array.isArray(wl.items) ? wl.items.slice() : []
|
|
3556
4185
|
}
|
|
3557
4186
|
if (!wb) { renderWorkbench(); renderSessions(); return }
|
|
@@ -4085,16 +4714,18 @@ function showView(id, pluginRoute = 'manage') {
|
|
|
4085
4714
|
if (window.DshWorkflow?.isMounted() && id === 'view-overview') id = 'view-sessions'
|
|
4086
4715
|
if (id !== 'view-chat') conversationView?.pause()
|
|
4087
4716
|
if (state.view === 'view-chat' && id !== 'view-chat' && state.current) void archiveEmptySessionOnLeave(state.current)
|
|
4717
|
+
if (state.view === 'view-schedule' && id !== 'view-schedule') hostSchedule?.leave()
|
|
4088
4718
|
state.view = id
|
|
4089
4719
|
window.DshFileInbox?.render()
|
|
4090
4720
|
window.DshSessionDeck?.refresh()
|
|
4091
4721
|
document.body?.classList.toggle('workflow-at-start', !!window.DshWorkflow?.isMounted() && id === 'view-sessions')
|
|
4092
|
-
for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
|
|
4722
|
+
for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings', 'view-schedule']) $(v).classList.toggle('hidden', v !== id)
|
|
4723
|
+
if (id === 'view-schedule') void hostSchedule?.refresh(true)
|
|
4093
4724
|
if (id === 'view-chat') conversationView?.resume()
|
|
4094
4725
|
document.querySelectorAll('.ds-nav-item').forEach(b => b.classList.toggle('active', b.dataset.view === id))
|
|
4095
4726
|
if (narrowSidebarQuery.matches) setMobileSidebar(false)
|
|
4096
4727
|
window.DshMotion?.view($(id))
|
|
4097
|
-
const titles = { 'view-overview': 'ds.overview', 'view-sessions': 'ds.sessions', 'view-chat': 'ds.sessions', 'view-files': 'ds.files', 'view-settings': 'ds.settings', 'view-plugins': 'ds.plugins' }
|
|
4728
|
+
const titles = { 'view-overview': 'ds.overview', 'view-sessions': 'ds.sessions', 'view-chat': 'ds.sessions', 'view-files': 'ds.files', 'view-settings': 'ds.settings', 'view-plugins': 'ds.plugins', 'view-schedule': 'hostSchedule.title' }
|
|
4098
4729
|
if (id === 'view-chat') { const s = state.byId.get(state.current); $('ds-title').textContent = s ? titleOf(s) : t('ds.sessions') }
|
|
4099
4730
|
else $('ds-title').textContent = t(titles[id])
|
|
4100
4731
|
if (id === 'view-overview') {startOverviewDetection(true);renderOverviewDesktop()}
|
|
@@ -4190,7 +4821,7 @@ function updateConn() {
|
|
|
4190
4821
|
|
|
4191
4822
|
function bindSessionDialogs() {
|
|
4192
4823
|
const actions=$('session-actions'), info=$('session-info');
|
|
4193
|
-
$('btn-session-more').addEventListener('click',()=>actions.showModal());
|
|
4824
|
+
$('btn-session-more').addEventListener('click',()=>{if(typeof refreshSessionAdminActions === 'function')refreshSessionAdminActions();actions.showModal()});
|
|
4194
4825
|
actions.addEventListener('click',e=>{if(e.target===actions)actions.close();else if(e.target.closest('button'))actions.close()},true);
|
|
4195
4826
|
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('ds.noWorkspace');$('session-info-id').textContent=s.sessionId;$('btn-copy-session-workspace').disabled=!s.cwd;info.showModal()};
|
|
4196
4827
|
$('ds-title').addEventListener('click',openInfo);
|
|
@@ -4289,7 +4920,8 @@ function bindUi() {
|
|
|
4289
4920
|
readSkills: sessionId => rpc('skills.list', { sessionId }, 5000),
|
|
4290
4921
|
})
|
|
4291
4922
|
composer.addEventListener('keydown', (e) => {
|
|
4292
|
-
if (
|
|
4923
|
+
if (e.defaultPrevented || e.key !== 'Enter' || e.isComposing || composerTools?.keydown(e)) return
|
|
4924
|
+
if (!e.shiftKey) { e.preventDefault(); sendMessage() }
|
|
4293
4925
|
})
|
|
4294
4926
|
renderPresetMenuDesktop()
|
|
4295
4927
|
renderPresetSummary()
|
|
@@ -4297,9 +4929,13 @@ function bindUi() {
|
|
|
4297
4929
|
$('cmd-menu').addEventListener('click', (e) => {
|
|
4298
4930
|
const item = e.target.closest('[data-ds-cmd]')
|
|
4299
4931
|
if (item) {
|
|
4300
|
-
const
|
|
4301
|
-
|
|
4302
|
-
|
|
4932
|
+
const command = String(item.dataset.dsCmd || '').replace(/^\/+/, '')
|
|
4933
|
+
if (typeof composerTools === 'undefined' || !composerTools?.insertCommand?.(command)) {
|
|
4934
|
+
const input = $('composer')
|
|
4935
|
+
if (input.value.trim()) input.value = '/' + command + ' ' + input.value
|
|
4936
|
+
else input.value = '/' + command + ' '
|
|
4937
|
+
input.focus()
|
|
4938
|
+
}
|
|
4303
4939
|
$('cmd-menu').classList.add('hidden')
|
|
4304
4940
|
}
|
|
4305
4941
|
})
|
|
@@ -4422,7 +5058,7 @@ function bindUi() {
|
|
|
4422
5058
|
$('btn-lang').addEventListener('click', () => {
|
|
4423
5059
|
I18N.setLang(I18N.lang === 'zh' ? 'en' : 'zh')
|
|
4424
5060
|
$('btn-lang').textContent = I18N.lang === 'zh' ? 'EN' : '中文'
|
|
4425
|
-
renderServers(); renderSessions(); renderNotifStack(); renderOverviewDesktop(); updateConn(); themeApply(); void refreshInsightEntry()
|
|
5061
|
+
renderServers(); renderSessions(); renderNotifStack(); renderOverviewDesktop(); updateConn(); if(typeof updateBcControlLabels === 'function')updateBcControlLabels(); if(typeof updateTurnDiffSettingLabel === 'function')updateTurnDiffSettingLabel(); if (state.current) { if(typeof refreshPlanReview === 'function')refreshPlanReview(); renderHistory(true) }; themeApply(); void refreshInsightEntry()
|
|
4426
5062
|
})
|
|
4427
5063
|
$('fs-up').addEventListener('click', fsUp)
|
|
4428
5064
|
$('fs-root').addEventListener('change', (event) => {
|
|
@@ -4471,10 +5107,14 @@ async function start() {
|
|
|
4471
5107
|
}
|
|
4472
5108
|
$('token-desc').textContent = state.token ? '● ' + state.token.slice(0, 12) + '…' : t('ds.toastAuth')
|
|
4473
5109
|
bindUi()
|
|
5110
|
+
if (typeof initBcFeatures === 'function') initBcFeatures()
|
|
4474
5111
|
window.DshImagePreview?.configure?.({ resolvePath: chatImageRequest, resolveAttachment: chatImageAttachment, capture: captureChatImage })
|
|
4475
5112
|
if (!state.token) { showView('view-settings'); $('desktop-token-input').focus() }
|
|
4476
5113
|
renderWorkbench()
|
|
4477
5114
|
updateConn()
|
|
5115
|
+
// Restore the startup connection's list before any network wait; the state
|
|
5116
|
+
// setter's queued restore is not enough to clear an old host's DOM on switch.
|
|
5117
|
+
if (state.token) restoreCachedSessionList()
|
|
4478
5118
|
checkNotesOnStart()
|
|
4479
5119
|
if (state.token) {
|
|
4480
5120
|
if (!doctorSessionHandoff) await selectFastestServer({ silent: true, reconnect: false })
|
|
@@ -4485,6 +5125,7 @@ async function start() {
|
|
|
4485
5125
|
}
|
|
4486
5126
|
overviewStarting=false
|
|
4487
5127
|
renderOverviewDesktop()
|
|
5128
|
+
if (typeof initTurnDiffSetting === 'function') initTurnDiffSetting()
|
|
4488
5129
|
}
|
|
4489
5130
|
|
|
4490
5131
|
start()
|
|
@@ -4526,6 +5167,7 @@ function mountWorkflowDesktop() {
|
|
|
4526
5167
|
const connection=captureConnection(),scope=historyCacheScope()
|
|
4527
5168
|
cancelHistoryLoad()
|
|
4528
5169
|
await window.DshImageCache.clear(scope);await window.DshHistory.cacheClear(scope)
|
|
5170
|
+
clearSessionCache(scope)
|
|
4529
5171
|
if(!connection.valid())return
|
|
4530
5172
|
const current=currentServerEntry();if(current)state.servers=state.servers.filter(s=>s.id!==current.id)
|
|
4531
5173
|
state.groupActive[state.activeGroup]='';state.token='';state.server='';LS.del('token');LS.del('server');saveServers()
|
|
@@ -4534,6 +5176,7 @@ function mountWorkflowDesktop() {
|
|
|
4534
5176
|
const results=[]
|
|
4535
5177
|
if(kind!=='images')cancelHistoryLoad()
|
|
4536
5178
|
if(kind!=='images')results.push(await window.DshHistory.cacheClear())
|
|
5179
|
+
if(kind!=='images')results.push(clearAllSessionCaches())
|
|
4537
5180
|
if(kind!=='history')results.push(await window.DshImageCache.clear())
|
|
4538
5181
|
if(kind==='all'){window.DshWorkflow.clearStorage();location.reload()}
|
|
4539
5182
|
else if(results.includes(false))toast(en?'Some caches could not be cleared. Retry shortly.':'部分缓存未能清除,请稍后重试。','err')
|