dsh-remote-plugin 0.7.4 → 0.7.6
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 +29 -48
- package/README.md +29 -48
- package/apk/dsh-remote.apk +0 -0
- package/gateway.cjs +3 -1
- package/index.mjs +28 -0
- package/package.json +4 -2
- package/plugin-center.mjs +126 -26
- package/public/app.js +189 -37
- package/public/chat-files.js +85 -0
- package/public/desktop/desktop.css +21 -2
- package/public/desktop/desktop.html +9 -0
- package/public/desktop/desktop.js +107 -32
- package/public/extensions.css +1 -0
- package/public/extensions.js +103 -0
- package/public/history.js +31 -10
- package/public/index.html +12 -3
- package/public/insights.css +2 -0
- package/public/insights.js +50 -23
- package/public/md.js +26 -18
- package/public/plugin-center.css +7 -3
- package/public/plugin-center.js +76 -18
- package/public/skills.css +81 -0
- package/public/skills.js +191 -0
- package/public/styles.css +27 -2
- package/public/theme-vars.css +5 -0
- package/public/update.json +8 -8
- package/public/version.json +1 -1
- package/session-file.mjs +34 -0
- package/skills.mjs +53 -0
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
<link rel="stylesheet" href="../theme-vars.css">
|
|
9
9
|
<link rel="stylesheet" href="desktop.css">
|
|
10
10
|
<link rel="stylesheet" href="../plugin-center.css">
|
|
11
|
+
<link rel="stylesheet" href="../skills.css">
|
|
12
|
+
<link rel="stylesheet" href="../extensions.css">
|
|
11
13
|
<link rel="stylesheet" href="../insights.css">
|
|
12
14
|
</head>
|
|
13
15
|
<body>
|
|
@@ -539,6 +541,8 @@
|
|
|
539
541
|
'ds.attention': '需要你处理', 'ds.runtime': '运行指标', 'ds.recentActivity': '近期活动', 'ds.dshVersion': 'DSH 版本', 'ds.gatewayStatus': '网关状态', 'ds.activeSessions': '活跃会话', 'ds.connectionMode': '连接模式', 'ds.liveWs': '实时 WS', 'ds.poll': '降级轮询', 'ds.running': '运行中', 'ds.noReason': '无说明', 'ds.noActivity': '暂无后台活动', 'ds.noSessions': '暂无会话', 'ds.refreshOverview': '刷新总览', 'ds.pendingCount': '{n} 项待处理', 'ds.activeCount': '{n} 个活跃会话', 'ds.nothingPending': '暂无事项', 'ds.action.openSession': '打开最近会话', 'ds.action.newSession': '新建会话', 'ds.action.attention': '处理待办', 'ds.action.connect': '去设置连接', 'ds.action.refresh': '重新检查连接',
|
|
540
542
|
'ds.sortLabel': '会话排序', 'ds.sortTime': '按时间', 'ds.sortWorkspace': '按工作区', 'ds.workspace': '工作区', 'ds.workspaceUnknown': '未指定工作区', 'ds.wbOrderSaved': '顺序已保存到当前设备',
|
|
541
543
|
'ds.insights': '上下文与费用',
|
|
544
|
+
'ds.insightsContext': '上下文分析',
|
|
545
|
+
'ds.insightsCost': '费用与额度',
|
|
542
546
|
'ds.files': '文件传输', 'ds.plugins': '插件', 'ds.settings': '设置', 'ds.stats': '统计', 'ds.menu': '导航',
|
|
543
547
|
'ds.send': '发送', 'ds.composerPlaceholder': '输入消息,Enter 发送…', 'ds.composerRunning': '运行中…', 'ds.presets': '预设', 'ds.sessionRename': '重命名会话', 'ds.sessionRenameTitle': '重命名会话', 'ds.sessionRenamePlaceholder': '输入新的会话名称', 'ds.sessionRenameConfirm': '保存', 'ds.sessionRenameFailed': '重命名失败', 'ds.sessionRenameEmpty': '会话名称不能为空', 'ds.sessionRenamed': '会话名称已更新', 'ds.sessionArchive': '归档', 'ds.sessionArchiveConfirm': '归档这个会话?归档后可在“显示已归档”中打开。', 'ds.sessionArchived': '会话已归档', 'ds.sessionStop': '停止本轮', 'ds.sessionStopConfirm': '停止当前回合?排队中的消息不会被删除。', 'ds.sessionStopFailed': '停止失败', 'ds.sessionStopRequested': '已请求停止本轮', 'ds.sessionRecovering': '恢复会话中…', 'ds.sessionReady': '会话已恢复', 'ds.sessionRecoveryFailed': '会话恢复失败',
|
|
544
548
|
'ds.commands': '指令',
|
|
@@ -646,6 +650,8 @@
|
|
|
646
650
|
'ds.attention': 'Needs attention', 'ds.runtime': 'Runtime metrics', 'ds.recentActivity': 'Recent activity', 'ds.dshVersion': 'DSH version', 'ds.gatewayStatus': 'Gateway status', 'ds.activeSessions': 'Active sessions', 'ds.connectionMode': 'Connection mode', 'ds.liveWs': 'Live WS', 'ds.poll': 'Degraded polling', 'ds.running': 'Running', 'ds.noReason': 'No reason given', 'ds.noActivity': 'No background activity', 'ds.noSessions': 'No sessions yet', 'ds.refreshOverview': 'Refresh overview', 'ds.pendingCount': '{n} pending', 'ds.activeCount': '{n} active sessions', 'ds.nothingPending': 'Nothing pending', 'ds.action.openSession': 'Open recent session', 'ds.action.newSession': 'New session', 'ds.action.attention': 'Review pending', 'ds.action.connect': 'Set up connection', 'ds.action.refresh': 'Check connection',
|
|
647
651
|
'ds.sortLabel': 'Session sort', 'ds.sortTime': 'By time', 'ds.sortWorkspace': 'By workspace', 'ds.workspace': 'Workspace', 'ds.workspaceUnknown': 'No workspace', 'ds.wbOrderSaved': 'Order saved on this device',
|
|
648
652
|
'ds.insights': 'Context & costs',
|
|
653
|
+
'ds.insightsContext': 'Context analysis',
|
|
654
|
+
'ds.insightsCost': 'Cost & quotas',
|
|
649
655
|
'ds.files': 'Files', 'ds.plugins': 'Plugins', 'ds.settings': 'Settings', 'ds.stats': 'Stats', 'ds.menu': 'Menu',
|
|
650
656
|
'ds.send': 'Send', 'ds.composerPlaceholder': 'Type a message, Enter to send…', 'ds.composerRunning': 'Running…', 'ds.presets': 'Presets', 'ds.sessionRename': 'Rename session', 'ds.sessionRenameTitle': 'Rename session', 'ds.sessionRenamePlaceholder': 'Enter a new session name', 'ds.sessionRenameConfirm': 'Save', 'ds.sessionRenameFailed': 'Rename failed', 'ds.sessionRenameEmpty': 'Session name cannot be empty', 'ds.sessionRenamed': 'Session name updated', 'ds.sessionArchive': 'Archive', 'ds.sessionArchiveConfirm': 'Archive this session? You can open it from “Show archived”.', 'ds.sessionArchived': 'Session archived', 'ds.sessionStop': 'Stop turn', 'ds.sessionStopConfirm': 'Stop the current turn? Queued messages will be kept.', 'ds.sessionStopFailed': 'Stop failed', 'ds.sessionStopRequested': 'Stop requested', 'ds.sessionRecovering': 'Restoring session…', 'ds.sessionReady': 'Session ready', 'ds.sessionRecoveryFailed': 'Session restore failed',
|
|
651
657
|
'ds.commands': 'Commands',
|
|
@@ -751,12 +757,15 @@
|
|
|
751
757
|
<script src="i18n.js"></script>
|
|
752
758
|
<link rel="stylesheet" href="../genui.css">
|
|
753
759
|
<script src="../genui.js"></script>
|
|
760
|
+
<script src="../chat-files.js"></script>
|
|
754
761
|
<script src="../md.js"></script>
|
|
755
762
|
<script src="../vendor/gsap/gsap.min.js"></script>
|
|
756
763
|
<script src="../motion.js"></script>
|
|
757
764
|
<script type="module" src="../morphicons-init.js"></script>
|
|
758
765
|
<script src="../plugin-center.js"></script>
|
|
766
|
+
<script src="../skills.js"></script>
|
|
759
767
|
<script src="../insights.js"></script>
|
|
768
|
+
<script src="../extensions.js"></script>
|
|
760
769
|
<script src="../sha256.js"></script>
|
|
761
770
|
<script src="../history.js"></script>
|
|
762
771
|
<script src="../link-check.js"></script>
|
|
@@ -80,6 +80,7 @@ const state = {
|
|
|
80
80
|
queues: {},
|
|
81
81
|
sessionActivity: new Set(),
|
|
82
82
|
queueSteering: {},
|
|
83
|
+
compactionBootAt: Date.now(),
|
|
83
84
|
compactions: {},
|
|
84
85
|
pendingCommands: {},
|
|
85
86
|
compactionPollTimer: null,
|
|
@@ -120,12 +121,15 @@ for (const key of ['server', 'token']) {
|
|
|
120
121
|
state.current = null; state.history = emptyDesktopHistory()
|
|
121
122
|
state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
|
|
122
123
|
state.approvals = []; state.questions = []; state.questionModal = null
|
|
123
|
-
state.queues = {}; state.queueSteering = {}; state.compactions = {}; state.pendingCommands = {}; state.sessionTurnTimes = {}
|
|
124
|
+
state.queues = {}; state.queueSteering = {}; state.compactions = {}; state.compactionTerminals = {}; state.compactionSeqs = {}; state.compactionBootAt = Date.now(); state.pendingCommands = {}; state.sessionTurnTimes = {}
|
|
124
125
|
state.sessionActivity = new Set()
|
|
125
126
|
state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
|
|
126
127
|
state.workspaces = []; state.archivedIds = []; state.wb = { bound: false, path: '', projects: null }
|
|
127
128
|
window.DshPluginCenter?.close()
|
|
128
129
|
window.DshInsights?.close()
|
|
130
|
+
window.DshExtensions?.close()
|
|
131
|
+
window.DshExtensions?.invalidateCapabilities()
|
|
132
|
+
if (typeof document !== 'undefined') document.getElementById('btn-insights')?.classList.add('hidden')
|
|
129
133
|
if(typeof document!=='undefined') {
|
|
130
134
|
const identityGeneration=connectionGeneration
|
|
131
135
|
queueMicrotask(()=>{if(identityGeneration===connectionGeneration&&typeof startOverviewDetection==='function')startOverviewDetection(true,true)})
|
|
@@ -1448,7 +1452,7 @@ function onMuxFrame(full) {
|
|
|
1448
1452
|
if (f.sessionId === state.current) { applyReasoningBaseline(f.partialReasoning); scheduleReasoningRender() }
|
|
1449
1453
|
return
|
|
1450
1454
|
}
|
|
1451
|
-
if (f.type === 'session/event') return onSessionEvent(f.sessionId, f.event)
|
|
1455
|
+
if (f.type === 'session/event') return onSessionEvent(f.sessionId, f.event, { replay: f.replay === true })
|
|
1452
1456
|
if (f.type === 'approval/requested') {
|
|
1453
1457
|
state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId)
|
|
1454
1458
|
state.approvals.push({ ...f, rpcId: full.rpcId })
|
|
@@ -1462,7 +1466,11 @@ function onMuxFrame(full) {
|
|
|
1462
1466
|
renderNotifStack()
|
|
1463
1467
|
return
|
|
1464
1468
|
}
|
|
1465
|
-
if (f.type === 'question/resolved') {
|
|
1469
|
+
if (f.type === 'question/resolved') {
|
|
1470
|
+
state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId)
|
|
1471
|
+
if (state.questionModal?.rpcId === f.questionRpcId) { $('modal-question').classList.add('hidden'); state.questionModal = null }
|
|
1472
|
+
renderNotifStack(); return
|
|
1473
|
+
}
|
|
1466
1474
|
if (f.type === 'session/queue') { state.queues[f.sessionId] = f.items || []; renderQueue(); return }
|
|
1467
1475
|
if (f.type === 'session/projection') { applyProjection(f.sessionId, f.key, f.value, f.seq); return }
|
|
1468
1476
|
if (f.type === 'stream/error') toast(f.error?.message || 'stream error', 'err')
|
|
@@ -1492,6 +1500,7 @@ function compactElapsed(startedAt) {
|
|
|
1492
1500
|
return minutes > 0 ? `${minutes}:${String(remain).padStart(2, '0')}` : `${remain}s`
|
|
1493
1501
|
}
|
|
1494
1502
|
function setCompactionStatus(sessionId, next) {
|
|
1503
|
+
state.compactionTerminals ||= {}
|
|
1495
1504
|
if (!sessionId) return
|
|
1496
1505
|
const previous = state.compactions[sessionId]
|
|
1497
1506
|
if (next?.active === true) {
|
|
@@ -1502,10 +1511,15 @@ function setCompactionStatus(sessionId, next) {
|
|
|
1502
1511
|
startedAt: Number(next.startedAt) || previous?.startedAt || Date.now(),
|
|
1503
1512
|
message: String(next.message || ''),
|
|
1504
1513
|
source: next.source || previous?.source || 'event',
|
|
1514
|
+
compactionId: next.compactionId || previous?.compactionId || '',
|
|
1515
|
+
notify: next.notify ?? previous?.notify ?? (next.source === 'command'),
|
|
1505
1516
|
}
|
|
1506
1517
|
} else {
|
|
1507
1518
|
delete state.compactions[sessionId]
|
|
1508
1519
|
if (previous?.active) {
|
|
1520
|
+
state.compactionTerminals[sessionId] = { startedAt: previous.startedAt, compactionId: previous.compactionId }
|
|
1521
|
+
}
|
|
1522
|
+
if (previous?.active && previous.notify && next?.notify !== false && ['complete', 'failed'].includes(next?.phase)) {
|
|
1509
1523
|
const command = previous.command || 'compact'
|
|
1510
1524
|
if (next?.phase === 'failed') toast(command === 'compact'
|
|
1511
1525
|
? t('ds.compactFailed', { msg: next.message || t('ds.sessionRecoveryFailed') })
|
|
@@ -1518,18 +1532,25 @@ function setCompactionStatus(sessionId, next) {
|
|
|
1518
1532
|
}
|
|
1519
1533
|
async function refreshCompactionStatus(sessionId = state.current) {
|
|
1520
1534
|
if (!sessionId) return
|
|
1535
|
+
const connection = captureConnection()
|
|
1521
1536
|
try {
|
|
1522
1537
|
const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(8000) : undefined
|
|
1523
|
-
const url = new URL(
|
|
1538
|
+
const url = new URL(connection.server + '/remote/api/command-status', location.href)
|
|
1524
1539
|
url.searchParams.set('sessionId', sessionId)
|
|
1525
|
-
const res = await fetch(url, { headers: { authorization: 'Bearer ' +
|
|
1540
|
+
const res = await fetch(url, { headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }, ...(signal ? { signal } : {}) })
|
|
1541
|
+
if (!connection.valid()) return
|
|
1526
1542
|
if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
|
|
1527
1543
|
if (!res.ok) return
|
|
1544
|
+
if (!connection.valid()) return
|
|
1528
1545
|
const body = await res.json().catch(() => null)
|
|
1546
|
+
if (!connection.valid()) return
|
|
1529
1547
|
const operation = body?.operation || body?.compact
|
|
1530
1548
|
if (!operation) return
|
|
1549
|
+
if (operation.startedAt && activeCompaction(sessionId)?.startedAt > Number(operation.startedAt)) return
|
|
1531
1550
|
const pending = state.pendingCommands[sessionId]
|
|
1532
|
-
if (operation.active) {
|
|
1551
|
+
if (operation.active === true) {
|
|
1552
|
+
const terminal = state.compactionTerminals?.[sessionId]
|
|
1553
|
+
if (terminal && Number(operation.startedAt) <= terminal.startedAt) return
|
|
1533
1554
|
delete state.pendingCommands[sessionId]
|
|
1534
1555
|
setCompactionStatus(sessionId, { ...operation, source: 'status' })
|
|
1535
1556
|
} else if (activeCompaction(sessionId) && activeCompaction(sessionId).source !== 'event') {
|
|
@@ -1555,14 +1576,25 @@ function ensureCompactionMonitoring() {
|
|
|
1555
1576
|
if (compact && compact.source !== 'event') void refreshCompactionStatus()
|
|
1556
1577
|
}, 3000)
|
|
1557
1578
|
}
|
|
1558
|
-
function observeCompactionEvent(sessionId, event) {
|
|
1559
|
-
if (event
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1579
|
+
function observeCompactionEvent(sessionId, event, meta = {}) {
|
|
1580
|
+
if (!event || !sessionId || !['compaction/start','compaction/end','session/end-seed'].includes(event.type)) return
|
|
1581
|
+
state.compactionSeqs ||= {}; state.compactionBootAt ||= Date.now()
|
|
1582
|
+
const seq = Number(event.seq), previous = activeCompaction(sessionId)
|
|
1583
|
+
if (seq > 0 && seq <= (state.compactionSeqs[sessionId] || 0)) return
|
|
1584
|
+
const id = event.data?.compactionId || ''
|
|
1585
|
+
if (event.type === 'compaction/end' && previous?.compactionId && previous.compactionId !== id) return
|
|
1586
|
+
if (seq > 0) state.compactionSeqs[sessionId] = seq
|
|
1587
|
+
const time = typeof event.time === 'number' ? event.time : Date.parse(event.time)
|
|
1588
|
+
if (event.type === 'compaction/start') {
|
|
1589
|
+
setCompactionStatus(sessionId, { active: true, phase: 'running', compactionId: id,
|
|
1590
|
+
startedAt: previous?.startedAt || (Number.isFinite(time) ? time : Date.now()), source: previous?.source || 'event',
|
|
1591
|
+
notify: meta.replay ? false : previous?.notify || Number.isFinite(time) && time >= state.compactionBootAt })
|
|
1592
|
+
} else {
|
|
1593
|
+
setCompactionStatus(sessionId, { active: false, phase: event.type === 'session/end-seed' ? 'interrupted' : event.data?.error ? 'failed' : 'complete',
|
|
1594
|
+
message: event.data?.error || '', ...(meta.replay || event.type === 'session/end-seed' ? { notify: false } : {}) })
|
|
1564
1595
|
}
|
|
1565
1596
|
}
|
|
1597
|
+
|
|
1566
1598
|
function hydrateSessionProjections(sessionId, projections) {
|
|
1567
1599
|
const s = state.byId.get(sessionId)
|
|
1568
1600
|
if (!s || !projections || typeof projections !== 'object') return
|
|
@@ -1626,9 +1658,36 @@ function resyncAfterStreamOpen() {
|
|
|
1626
1658
|
void refreshSessions().then(() => resyncCurrentSession())
|
|
1627
1659
|
}
|
|
1628
1660
|
function proj(s, key, d) { return s?.projections?.values?.[key] ?? d }
|
|
1629
|
-
function
|
|
1630
|
-
|
|
1631
|
-
|
|
1661
|
+
function optionalPluginConfig(connection = captureConnection()) {
|
|
1662
|
+
return { connection, valid: connection.valid, url: path => connection.server + path,
|
|
1663
|
+
headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() } }
|
|
1664
|
+
}
|
|
1665
|
+
function availableInsightTabs(capabilities) {
|
|
1666
|
+
return [...(capabilities.context ? ['context'] : []), ...(capabilities.cost ? ['cost'] : [])]
|
|
1667
|
+
}
|
|
1668
|
+
async function refreshInsightEntry() {
|
|
1669
|
+
const control = $('btn-insights'), id = state.current, connection = captureConnection()
|
|
1670
|
+
if (!control || !id || !connection.token || !window.DshExtensions) { control?.classList.add('hidden'); return }
|
|
1671
|
+
const capabilities = await window.DshExtensions.getCapabilities(optionalPluginConfig(connection))
|
|
1672
|
+
if (!connection.valid() || state.current !== id) return
|
|
1673
|
+
const tabs = availableInsightTabs(capabilities)
|
|
1674
|
+
control.classList.toggle('hidden', !tabs.length)
|
|
1675
|
+
const label = t(tabs.length === 2 ? 'ds.insights' : tabs[0] === 'cost' ? 'ds.insightsCost' : 'ds.insightsContext')
|
|
1676
|
+
control.textContent = label; control.title = label; control.setAttribute('aria-label', label)
|
|
1677
|
+
}
|
|
1678
|
+
async function openInsights(tab = 'context', fullPage = false) {
|
|
1679
|
+
const connection = captureConnection(), id = state.current
|
|
1680
|
+
const capabilities = await window.DshExtensions.getCapabilities(optionalPluginConfig(connection))
|
|
1681
|
+
if (!connection.valid() || state.current !== id || !id) return
|
|
1682
|
+
const allowedTabs = availableInsightTabs(capabilities)
|
|
1683
|
+
if (!allowedTabs.length) { void refreshInsightEntry(); return }
|
|
1684
|
+
window.DshInsights?.close()
|
|
1685
|
+
const view = fullPage ? conversationView : null, wasPaused = view?.paused
|
|
1686
|
+
view?.pause()
|
|
1687
|
+
window.DshInsights?.open({ tab, fullPage, allowedTabs, connection, url: path => connection.server + path,
|
|
1688
|
+
getSession: () => state.byId.get(state.current), getTitle: () => titleOf(state.byId.get(state.current)),
|
|
1689
|
+
onFullPage: selected => void openInsights(selected, true),
|
|
1690
|
+
onClose: () => { if (view && !wasPaused && connection.valid() && state.current === id && state.view === 'view-chat') view.resume() } })
|
|
1632
1691
|
}
|
|
1633
1692
|
function sessionTitleValue(s) {
|
|
1634
1693
|
const value = proj(s, 'title', '')
|
|
@@ -1676,8 +1735,8 @@ function setGoalCollapsed(sessionId, goal, collapsed) {
|
|
|
1676
1735
|
if (collapsed) next.push({ sessionId, goalId })
|
|
1677
1736
|
LS.set(COLLAPSED_GOALS_KEY, JSON.stringify(next.slice(-100)))
|
|
1678
1737
|
}
|
|
1679
|
-
function onSessionEvent(sessionId, event) {
|
|
1680
|
-
observeCompactionEvent(sessionId, event)
|
|
1738
|
+
function onSessionEvent(sessionId, event, meta = {}) {
|
|
1739
|
+
observeCompactionEvent(sessionId, event, meta)
|
|
1681
1740
|
if (event?.type === 'turn/start' || event?.type === 'turn/end') {
|
|
1682
1741
|
noteSessionTurnTime(sessionId, event)
|
|
1683
1742
|
renderSessions()
|
|
@@ -1919,7 +1978,7 @@ function getConversationView() {
|
|
|
1919
1978
|
if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
|
|
1920
1979
|
html:entry=>eventHtml(entry),
|
|
1921
1980
|
older:()=>loadHistory(false),olderLabel:()=>t('ds.historyEarlier'),loadingLabel:()=>t('ds.historyLoadingEarlier'),live:partialReasoningHtml,
|
|
1922
|
-
changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end
|
|
1981
|
+
changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end;const latest=$('btn-history-latest');if(latest){latest.classList.toggle('hidden',!view.reading&&view.end>=view.entries.length&&!state.history.tailEvicted);latest.textContent=t('ds.historyLatest')+(view.unread?' ('+view.unread+')':view.hasPending?' · '+(I18N.lang==='en'?'New content':'有新内容'):'');}},
|
|
1923
1982
|
scrolled:()=>{}
|
|
1924
1983
|
})
|
|
1925
1984
|
return conversationView
|
|
@@ -2086,7 +2145,8 @@ function partialReasoningHtml() {
|
|
|
2086
2145
|
function safeJson(v) { try { return JSON.stringify(v, null, 2) } catch { return String(v) } }
|
|
2087
2146
|
function blockHtml(b) {
|
|
2088
2147
|
if (!b) return ''
|
|
2089
|
-
if (b.type === 'text') return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '') : esc(b.text ?? '')}</div>`
|
|
2148
|
+
if (b.type === 'text') return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true }) : esc(b.text ?? '')}</div>`
|
|
2149
|
+
if (b.type === 'file' && typeof window !== 'undefined' && window.DshChatFiles) return window.DshChatFiles.render(b)
|
|
2090
2150
|
if (b.type === 'file') return `<div class="ds-tool">📎 ${esc(b.attachment?.name || b.name || 'file')} <small>${esc(b.attachment?.bytes ?? b.bytes ?? '')} bytes</small></div>`
|
|
2091
2151
|
if (b.type === 'thinking' || b.type === 'reasoning') return `<details><summary>${esc(t('block.thinking'))}</summary><div style="opacity:.82">${esc(b.text ?? b.content ?? '')}</div></details>`
|
|
2092
2152
|
if (b.type === 'tool-call') return `<div>🔧 ${esc(b.name || '')}</div>`
|
|
@@ -2153,7 +2213,7 @@ let sessionCardsRenderGeneration = 0
|
|
|
2153
2213
|
async function renderSessionCards() {
|
|
2154
2214
|
const connection = captureConnection()
|
|
2155
2215
|
window.DshInsights?.update()
|
|
2156
|
-
|
|
2216
|
+
void refreshInsightEntry()
|
|
2157
2217
|
const renderGeneration = ++sessionCardsRenderGeneration
|
|
2158
2218
|
const sessionId = state.current
|
|
2159
2219
|
const box = $('session-cards')
|
|
@@ -2534,14 +2594,13 @@ function renderSessionPendingDesktop() {
|
|
|
2534
2594
|
<div class="ds-notif-body">${esc(desktopApprovalDetail(item))}</div>
|
|
2535
2595
|
<div class="ds-notif-actions"><button type="button" class="ds-btn allow" data-session-approve="1">${t('ds.allow')}</button><button type="button" class="ds-btn reject" data-session-approve="0">${t('ds.reject')}</button></div>
|
|
2536
2596
|
</article>`
|
|
2537
|
-
return `<
|
|
2538
|
-
<
|
|
2539
|
-
<
|
|
2540
|
-
|
|
2541
|
-
</article>`
|
|
2597
|
+
return `<button type="button" class="ds-notif-card question" data-session-question="${esc(item.rpcId)}" aria-haspopup="dialog">
|
|
2598
|
+
<span class="ds-question-card-head"><span class="ds-notif-head">❓ ${esc(item.questions?.[0]?.header || t('ds.questionNotify'))}</span><span class="ds-btn">${t('ds.submit')}</span></span>
|
|
2599
|
+
<span class="ds-question-summary">${esc(questionSummary(item))}</span>
|
|
2600
|
+
</button>`
|
|
2542
2601
|
}).join('')}</div>`
|
|
2543
2602
|
box.querySelectorAll('[data-session-approve]').forEach(button => button.addEventListener('click', () => approveApproval(button.closest('[data-session-approval]')?.dataset.sessionApproval || '', button.dataset.sessionApprove === '1')))
|
|
2544
|
-
box.querySelectorAll('[data-session-
|
|
2603
|
+
box.querySelectorAll('[data-session-question]').forEach(button => button.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === button.dataset.sessionQuestion))))
|
|
2545
2604
|
}
|
|
2546
2605
|
function renderNotifStack() {
|
|
2547
2606
|
const stack = $('notif-stack')
|
|
@@ -2604,17 +2663,27 @@ async function approveApproval(id, allow) {
|
|
|
2604
2663
|
state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
|
|
2605
2664
|
renderNotifStack()
|
|
2606
2665
|
}
|
|
2666
|
+
function questionSummary(q) {
|
|
2667
|
+
return (q.questions || []).map(item => String(item.question || '').replace(/\[([^\]]+)\]\([^)]+\)/g, '$1').replace(/[*_`#>]/g, '')).join(' / ').replace(/\s+/g, ' ').trim().slice(0, 240)
|
|
2668
|
+
}
|
|
2669
|
+
|
|
2670
|
+
function questionMarkup(item) {
|
|
2671
|
+
const text = String(item.question || '')
|
|
2672
|
+
return (item.header ? `<strong>${esc(item.header)}</strong>` : '') + (window.mdToHtml ? window.mdToHtml(text, { richContent: false, fileLinks: true }) : esc(text))
|
|
2673
|
+
}
|
|
2674
|
+
|
|
2607
2675
|
function openQuestionModal(q) {
|
|
2608
2676
|
if (!q) return
|
|
2609
2677
|
state.questionModal = q
|
|
2610
2678
|
$('question-body').innerHTML = q.questions.map((item, i) => `
|
|
2611
2679
|
<div class="ds-q-item">
|
|
2612
|
-
<div class="ds-q-text">${
|
|
2680
|
+
<div class="ds-q-text md">${questionMarkup(item)}</div>
|
|
2613
2681
|
${(item.options || []).map((o, j) => `
|
|
2614
2682
|
<label class="ds-q-option"><input type="${item.multiSelect ? 'checkbox' : 'radio'}" name="q${i}" value="${esc(o.label)}"><span>${esc(o.label)}${o.description ? `<div class="muted">${esc(o.description)}</div>` : ''}</span></label>`).join('')}
|
|
2615
2683
|
<textarea rows="2" placeholder="${t('ds.questionCustom')}" data-qcustom="${i}"></textarea>
|
|
2616
2684
|
</div>`).join('')
|
|
2617
2685
|
$('modal-question').classList.remove('hidden')
|
|
2686
|
+
$('question-body').scrollTop = 0
|
|
2618
2687
|
}
|
|
2619
2688
|
async function submitQuestion() {
|
|
2620
2689
|
const connection = captureConnection()
|
|
@@ -2746,7 +2815,6 @@ async function createWorkspace() {
|
|
|
2746
2815
|
button.disabled = true
|
|
2747
2816
|
try {
|
|
2748
2817
|
const res = await fetch(fsApiUrl('/mkdir', { path: parent, name }), { method: 'POST', headers: fsHeaders() })
|
|
2749
|
-
if (!connection.valid()) return
|
|
2750
2818
|
if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
|
|
2751
2819
|
const data = await res.json().catch(() => ({}))
|
|
2752
2820
|
if (!connection.valid()) return
|
|
@@ -3476,16 +3544,18 @@ function setMobileSidebar(open) {
|
|
|
3476
3544
|
$('ds-app')?.classList.toggle('mobile-nav-open', visible)
|
|
3477
3545
|
}
|
|
3478
3546
|
|
|
3479
|
-
function openDesktopPlugins() {
|
|
3547
|
+
function openDesktopPlugins(route = 'manage') {
|
|
3480
3548
|
const connection=captureConnection()
|
|
3481
3549
|
if(!connection.token){$('desktop-plugin-page').textContent=t('ds.toastAuth');return}
|
|
3482
|
-
window.
|
|
3550
|
+
window.DshExtensions.mount({connection,getSession:()=>state.byId.get(state.current),getTitle:()=>titleOf(state.byId.get(state.current)),openContext:()=>void openInsights('context',true),scrollTop:()=>{$('view-plugins').scrollTop=0},url:path=>connection.server+path,headers:{authorization:'Bearer '+connection.token,'x-dsh-remote-client':'web',...clientIdHeaders()},valid:connection.valid},$('desktop-plugin-page'),route)
|
|
3483
3551
|
}
|
|
3484
3552
|
|
|
3485
3553
|
function showView(id) {
|
|
3554
|
+
if (id !== 'view-chat') conversationView?.pause()
|
|
3486
3555
|
if (state.view === 'view-chat' && id !== 'view-chat' && state.current) void archiveEmptySessionOnLeave(state.current)
|
|
3487
3556
|
state.view = id
|
|
3488
3557
|
for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
|
|
3558
|
+
if (id === 'view-chat') conversationView?.resume()
|
|
3489
3559
|
document.querySelectorAll('.ds-nav-item').forEach(b => b.classList.toggle('active', b.dataset.view === id))
|
|
3490
3560
|
if (narrowSidebarQuery.matches) setMobileSidebar(false)
|
|
3491
3561
|
window.DshMotion?.view($(id))
|
|
@@ -3497,7 +3567,7 @@ function showView(id) {
|
|
|
3497
3567
|
if (id === 'view-files' && !state.fs.loaded) loadFs(null, true)
|
|
3498
3568
|
if (id === 'view-settings') showSettingsHome()
|
|
3499
3569
|
if (id === 'view-plugins') openDesktopPlugins()
|
|
3500
|
-
else window.
|
|
3570
|
+
else window.DshExtensions?.close()
|
|
3501
3571
|
updateSessionActions()
|
|
3502
3572
|
}
|
|
3503
3573
|
|
|
@@ -3700,6 +3770,11 @@ function bindUi() {
|
|
|
3700
3770
|
if (!e.target.closest('#model-menu') && !e.target.closest('#btn-model')) $('model-menu')?.classList.add('hidden')
|
|
3701
3771
|
})
|
|
3702
3772
|
$('btn-stats-top').addEventListener('click', toggleStatsDrawer)
|
|
3773
|
+
for (const id of ['history', 'question-body']) window.DshChatFiles?.bind($(id), () => {
|
|
3774
|
+
const c=captureConnection(),sessionId=id==='history'?state.current:state.questionModal?.sessionId
|
|
3775
|
+
return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:false,headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,
|
|
3776
|
+
valid:()=>c.valid()&&sessionId===(id==='history'?state.current:state.questionModal?.sessionId) }
|
|
3777
|
+
})
|
|
3703
3778
|
$('btn-insights').addEventListener('click', () => openInsights())
|
|
3704
3779
|
$('stats-drawer-close').addEventListener('click', toggleStatsDrawer)
|
|
3705
3780
|
// 赞赏支持
|
|
@@ -3803,7 +3878,7 @@ function bindUi() {
|
|
|
3803
3878
|
$('btn-lang').addEventListener('click', () => {
|
|
3804
3879
|
I18N.setLang(I18N.lang === 'zh' ? 'en' : 'zh')
|
|
3805
3880
|
$('btn-lang').textContent = I18N.lang === 'zh' ? 'EN' : '中文'
|
|
3806
|
-
renderServers(); renderSessions(); renderNotifStack(); renderOverviewDesktop(); updateConn(); themeApply()
|
|
3881
|
+
renderServers(); renderSessions(); renderNotifStack(); renderOverviewDesktop(); updateConn(); themeApply(); void refreshInsightEntry()
|
|
3807
3882
|
})
|
|
3808
3883
|
$('fs-up').addEventListener('click', fsUp)
|
|
3809
3884
|
$('fs-root').addEventListener('change', (event) => {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
.ext-page{min-width:0;width:100%;padding:16px;color:var(--dsr-text)}.ext-page.is-manage{padding:0}.ext-header{display:flex;gap:14px;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap}.ext-host{min-width:0;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dsr-muted);font-size:13px;line-height:1.7}.ext-header button{flex-shrink:0;white-space:nowrap;color:var(--dsr-text);background:var(--dsr-panel);border:1px solid var(--dsr-line);border-radius:12px;font:inherit;min-height:44px;padding:10px 14px;cursor:pointer}.ext-header button:focus-visible{outline:2px solid var(--dsr-accent);outline-offset:3px}.ext-page [hidden]{display:none!important}@media(max-width:620px){.ext-page{padding:8px 0}.ext-header{margin-bottom:18px}}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/* Optional plugin views. Entry points belong to installed plugins and session actions. */
|
|
2
|
+
'use strict';
|
|
3
|
+
window.DshExtensions = (() => {
|
|
4
|
+
let current, cache
|
|
5
|
+
const catalog = [
|
|
6
|
+
{ id: 'skills', name: '@linxin666/dsh-client-ui-skill-explorer', label: '打开技能中心' },
|
|
7
|
+
{ id: 'cost', name: 'dsh-cost-meter', label: '查看费用与额度' },
|
|
8
|
+
{ id: 'context', name: 'dsh-context', label: '查看当前会话上下文', session: true },
|
|
9
|
+
]
|
|
10
|
+
const empty = () => ({ known: false, skills: false, cost: false, context: false })
|
|
11
|
+
function capabilitiesOf(snapshot) {
|
|
12
|
+
if (snapshot?.ok !== true || !Array.isArray(snapshot.items) || !Array.isArray(snapshot.runtime)) return empty()
|
|
13
|
+
const result = { ...empty(), known: true }
|
|
14
|
+
for (const feature of catalog) {
|
|
15
|
+
const item = snapshot.items.find(row => row?.name === feature.name)
|
|
16
|
+
if (item?.enabled !== true || snapshot.runtimeAvailable !== true) continue
|
|
17
|
+
if (item.runtime != null && !Array.isArray(item.runtime)) continue
|
|
18
|
+
const runtime = [...(item.runtime || []), ...snapshot.runtime.filter(row => row?.name === feature.name)]
|
|
19
|
+
result[feature.id] = runtime.length > 0 && runtime.every(row => row && row.enabled !== false && row.phase === 'active')
|
|
20
|
+
}
|
|
21
|
+
return result
|
|
22
|
+
}
|
|
23
|
+
function featuresFor(snapshot, item, session = false) {
|
|
24
|
+
const available = capabilitiesOf(snapshot)
|
|
25
|
+
return catalog.filter(feature => feature.name === item.name && available[feature.id] && (!feature.session || session))
|
|
26
|
+
}
|
|
27
|
+
function identity(config) { return config.connection || config }
|
|
28
|
+
function same(config) {
|
|
29
|
+
const next = identity(config)
|
|
30
|
+
return cache && cache.connection.valid() && next.valid() && cache.connection.server === next.server && cache.connection.token === next.token
|
|
31
|
+
}
|
|
32
|
+
function remember(config, snapshot) {
|
|
33
|
+
if (!config.valid()) return
|
|
34
|
+
if (!same(config)) { cache?.controller?.abort(); cache = { connection: identity(config) } }
|
|
35
|
+
cache.value = capabilitiesOf(snapshot); cache.at = Date.now()
|
|
36
|
+
cache.serial = (cache.serial || 0) + 1
|
|
37
|
+
}
|
|
38
|
+
function invalidateCapabilities() { cache?.controller?.abort(); cache = null }
|
|
39
|
+
async function getCapabilities(config) {
|
|
40
|
+
if (!config.valid()) return empty()
|
|
41
|
+
if (!same(config)) { invalidateCapabilities(); cache = { connection: identity(config) } }
|
|
42
|
+
const record = cache
|
|
43
|
+
if (record.value && Date.now() - record.at < 15000) return record.value
|
|
44
|
+
if (record.task) return record.task
|
|
45
|
+
record.controller = new AbortController()
|
|
46
|
+
const serial = record.serial || 0
|
|
47
|
+
record.task = (async () => {
|
|
48
|
+
try {
|
|
49
|
+
const response = await fetch(config.url('/remote/api/plugins/state'), { headers: config.headers,
|
|
50
|
+
signal: AbortSignal.any([record.controller.signal, AbortSignal.timeout(15000)]) })
|
|
51
|
+
const body = await response.text()
|
|
52
|
+
if (body.length > 2 * 1024 * 1024) return empty()
|
|
53
|
+
const snapshot = JSON.parse(body)
|
|
54
|
+
if (!response.ok || !config.valid() || cache !== record || snapshot?.ok !== true) return empty()
|
|
55
|
+
if ((record.serial || 0) !== serial) return record.value || empty()
|
|
56
|
+
record.value = capabilitiesOf(snapshot); record.at = Date.now(); return record.value
|
|
57
|
+
} catch {
|
|
58
|
+
if (cache === record && config.valid() && (record.serial || 0) !== serial) return record.value || empty()
|
|
59
|
+
if (cache === record) { record.value = empty(); record.at = Date.now() }
|
|
60
|
+
return empty()
|
|
61
|
+
}
|
|
62
|
+
finally { record.task = null }
|
|
63
|
+
})()
|
|
64
|
+
return record.task
|
|
65
|
+
}
|
|
66
|
+
const node=(tag,text,cls)=>{const el=document.createElement(tag);if(text!=null)el.textContent=text;if(cls)el.className=cls;return el}
|
|
67
|
+
const stopViews=()=>{window.DshSkillsCenter?.close();window.DshInsights?.close()}
|
|
68
|
+
function close(){if(current){const old=current;current=null;stopViews();window.DshPluginCenter?.close();old.target.replaceChildren()}}
|
|
69
|
+
function mount(config,target,initial='manage') {
|
|
70
|
+
close()
|
|
71
|
+
const s={config,target,route:'manage',navigation:0};current=s
|
|
72
|
+
const valid=()=>current===s&&config.valid()
|
|
73
|
+
const root=node('section',null,'ext-page'),header=node('header',null,'ext-header'),back=node('button','← 返回插件列表'),hint=node('p',null,'ext-host'),content=node('div',null,'ext-content'),manager=node('div',null,'ext-manager'),view=node('div',null,'ext-view')
|
|
74
|
+
back.type='button';header.append(back,hint);content.append(manager,view);root.append(header,content);target.replaceChildren(root)
|
|
75
|
+
try{hint.textContent='当前主机 · '+new URL(config.connection.server).host}catch{hint.textContent='当前连接的主机'}
|
|
76
|
+
async function navigate(route) {
|
|
77
|
+
if(!valid())return
|
|
78
|
+
const navigation=++s.navigation
|
|
79
|
+
if(route==='home')route='manage'
|
|
80
|
+
if(route==='context'){config.openContext?.();return}
|
|
81
|
+
if(route!=='manage'){
|
|
82
|
+
const available=await getCapabilities(config)
|
|
83
|
+
if(!valid()||navigation!==s.navigation)return
|
|
84
|
+
if(!available[route]){navigate('manage');return}
|
|
85
|
+
if(s.route==='manage'){s.scroller=scrollParent(root);s.scroll=s.scroller?.scrollTop||0;window.DshPluginCenter?.pause()}
|
|
86
|
+
}
|
|
87
|
+
stopViews();s.route=route;view.replaceChildren();header.hidden=route==='manage';manager.hidden=route!=='manage';view.hidden=route==='manage';root.className='ext-page'+(route==='manage'?' is-manage':'')
|
|
88
|
+
if(route==='manage'){
|
|
89
|
+
if(!s.mounted){s.mounted=true;await window.DshPluginCenter.mount({...config,onFeature:navigate},manager)}
|
|
90
|
+
else {if(s.scroller)s.scroller.scrollTop=s.scroll;void window.DshPluginCenter.resume()}
|
|
91
|
+
}else if(route==='skills')await window.DshSkillsCenter.mount(config,view,{dedicated:true})
|
|
92
|
+
else window.DshInsights.mount({tab:'cost',hostOverview:true,allowedTabs:['cost'],connection:config.connection,url:config.url},view)
|
|
93
|
+
if(valid()&&route!=='manage')config.scrollTop?.()
|
|
94
|
+
}
|
|
95
|
+
back.addEventListener('click',()=>{if(valid())void navigate('manage')})
|
|
96
|
+
void navigate('manage').then(()=>{if(initial!=='manage'&&initial!=='home'&&valid())void navigate(initial)})
|
|
97
|
+
}
|
|
98
|
+
function scrollParent(el) {
|
|
99
|
+
for(let parent=el.parentElement;parent;parent=parent.parentElement)if(parent.scrollHeight>parent.clientHeight&&/auto|scroll/.test(getComputedStyle(parent).overflowY))return parent
|
|
100
|
+
return document.scrollingElement
|
|
101
|
+
}
|
|
102
|
+
return {mount,close,capabilitiesOf,featuresFor,getCapabilities,remember,invalidateCapabilities}
|
|
103
|
+
})()
|
package/public/history.js
CHANGED
|
@@ -29,8 +29,13 @@
|
|
|
29
29
|
this.more.addEventListener('click',()=>this.older())
|
|
30
30
|
this.empty=document.createElement('div'); this.empty.className='history-empty'
|
|
31
31
|
this.live=document.createElement('div'); this.live.className='history-live'
|
|
32
|
-
const intent=()=>{this.intentUntil=Date.now()+
|
|
33
|
-
|
|
32
|
+
const intent=()=>{this.intentUntil=Date.now()+1200}
|
|
33
|
+
const hold=()=>{intent();this.reading=true;this.options.changed?.(this)}
|
|
34
|
+
box.addEventListener('wheel',event=>{intent();if(event.deltaY<0)hold()},{passive:true})
|
|
35
|
+
box.addEventListener('touchstart',event=>{this.touchY=event.touches?.[0]?.clientY;this.lastScrollTop=box.scrollTop},{passive:true})
|
|
36
|
+
box.addEventListener('touchmove',event=>{const y=event.touches?.[0]?.clientY;intent();if(y>this.touchY)hold();this.touchY=y},{passive:true})
|
|
37
|
+
box.addEventListener('pointerdown',()=>{this.lastScrollTop=box.scrollTop;this.intentUntil=0;this.reading=true;this.options.changed?.(this)},{passive:true})
|
|
38
|
+
box.addEventListener('keydown',event=>{if(['ArrowUp','PageUp','Home'].includes(event.key))hold();else if(['ArrowDown','PageDown','End'].includes(event.key))intent()})
|
|
34
39
|
box.addEventListener('scroll',()=>{
|
|
35
40
|
if(this.suppress || this.frame)return
|
|
36
41
|
this.frame=requestAnimationFrame(()=>{this.frame=0;this.onScroll()})
|
|
@@ -41,14 +46,19 @@
|
|
|
41
46
|
for(const node of this.box.querySelectorAll('.history-entry'))if(node.getBoundingClientRect().bottom>=top+1)return {seq:Number(node.dataset.historySeq),top:node.getBoundingClientRect().top}
|
|
42
47
|
return null
|
|
43
48
|
}
|
|
49
|
+
get unread() {return Math.max(0,this.entries.length-this.end)}
|
|
50
|
+
get hasPending() {return this.unread>0||(this.pendingLive||'')!==(this.liveHtml||'')}
|
|
44
51
|
set(entries, {reset=false, follow=false, live='', hasMore=false, loading=false, emptyLabel=''}={}) {
|
|
52
|
+
if(this.paused){this.pending={entries:entries.slice(),options:{reset,follow,live,hasMore,loading,emptyLabel}};return}
|
|
53
|
+
this.pendingLive=live
|
|
54
|
+
// Reading is explicit user intent. A stream update never changes it by proximity.
|
|
55
|
+
if(this.reading&&!reset)live=this.liveHtml||''
|
|
45
56
|
if(!reset&&entries.length===this.entries.length&&entries.every((entry,i)=>entry===this.entries[i])&&hasMore===this.hasMore&&loading===this.loading&&(this.end===entries.length?live:'')===this.liveHtml){this.more.disabled=loading;this.more.textContent=loading?this.options.loadingLabel():this.options.olderLabel();this.domChanged=false;this.options.changed?.(this);return}
|
|
46
|
-
if(Date.now()<this.intentUntil)this.reading=this.box.scrollHeight-this.box.scrollTop-this.box.clientHeight>=180
|
|
47
57
|
const oldWidth=this.end-this.start
|
|
48
58
|
const anchor=this.anchor(), oldStart=this.entries[this.start]?.seq, oldEnd=this.entries[Math.max(this.start,this.end-1)]?.seq
|
|
49
59
|
this.entries=entries.slice(); this.hasMore=hasMore; this.loading=loading
|
|
50
60
|
if(reset || !this.end){this.end=entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE);this.reading=false}
|
|
51
|
-
else if(
|
|
61
|
+
else if(!this.reading && this.end>=this.previousLength){this.end=entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE)}
|
|
52
62
|
else {
|
|
53
63
|
let start=entries.findIndex(e=>e.seq===oldStart),end=entries.findIndex(e=>e.seq===oldEnd)
|
|
54
64
|
if(start<0)start=anchor?entries.findIndex(e=>e.seq===anchor.seq):0
|
|
@@ -57,7 +67,7 @@
|
|
|
57
67
|
this.previousLength=entries.length
|
|
58
68
|
this.empty.textContent=emptyLabel
|
|
59
69
|
this.more.textContent=loading?this.options.loadingLabel():this.options.olderLabel();this.more.disabled=loading;this.more.hidden=this.start===0&&!hasMore
|
|
60
|
-
this.liveHtml=this.end===entries.length?live:''
|
|
70
|
+
this.liveHtml=this.reading&&!reset ? this.liveHtml||'' : this.end===entries.length?live:''
|
|
61
71
|
this.render(anchor,reset || (!this.reading && this.end===entries.length))
|
|
62
72
|
}
|
|
63
73
|
render(anchor, bottom=false) {
|
|
@@ -85,28 +95,39 @@
|
|
|
85
95
|
else if(anchor){const current=this.nodes.get(anchor.seq)?.node;if(current?.parentNode===box)box.scrollTop+=current.getBoundingClientRect().top-anchor.top}
|
|
86
96
|
const active=new Set(slice.map(entry=>entry.seq));for(const seq of this.nodes.keys())if(!active.has(seq))this.nodes.delete(seq)
|
|
87
97
|
cancelAnimationFrame(this.releaseFrame);this.releaseFrame=requestAnimationFrame(()=>{this.suppress=false})
|
|
98
|
+
this.lastScrollTop=box.scrollTop
|
|
88
99
|
this.domChanged=changed
|
|
89
100
|
this.options.changed?.(this)
|
|
90
101
|
}
|
|
91
102
|
onScroll() {
|
|
92
103
|
const box=this.box
|
|
93
|
-
if(Date.now()<this.intentUntil)
|
|
104
|
+
if(Date.now()<this.intentUntil){
|
|
105
|
+
if(box.scrollTop<(this.lastScrollTop??box.scrollTop))this.reading=true
|
|
106
|
+
else if(box.scrollTop>(this.lastScrollTop??box.scrollTop)&&box.scrollHeight-box.scrollTop-box.clientHeight<=8&&this.end===this.entries.length)this.reading=false
|
|
107
|
+
}
|
|
108
|
+
this.lastScrollTop=box.scrollTop
|
|
94
109
|
if(box.scrollTop<80 && Date.now()<this.intentUntil)this.older()
|
|
95
|
-
else if(box.scrollHeight-box.scrollTop-box.clientHeight<120 && this.end<this.entries.length && Date.now()<this.intentUntil){const anchor=this.anchor();this.end=Math.min(this.entries.length,this.end+WINDOW_STEP);this.start=Math.max(0,this.end-WINDOW_SIZE);this.render(anchor)}
|
|
110
|
+
else if(box.scrollHeight-box.scrollTop-box.clientHeight<120 && this.end<this.entries.length && Date.now()<this.intentUntil){const anchor=this.anchor();this.end=Math.min(this.entries.length,this.end+WINDOW_STEP);this.start=Math.max(0,this.end-WINDOW_SIZE);this.liveHtml=this.end===this.entries.length?this.pendingLive||'':'';this.render(anchor)}
|
|
96
111
|
this.options.scrolled?.(this)
|
|
97
112
|
this.domChanged=false
|
|
98
113
|
this.options.changed?.(this)
|
|
99
114
|
}
|
|
100
115
|
async older() {
|
|
101
116
|
if(this.pendingOlder)return
|
|
102
|
-
if(this.start>0){const anchor=this.anchor();this.start=Math.max(0,this.start-WINDOW_STEP);this.end=Math.min(this.entries.length,this.start+WINDOW_SIZE);this.reading=true;this.render(anchor);return}
|
|
117
|
+
if(this.start>0){const anchor=this.anchor();this.start=Math.max(0,this.start-WINDOW_STEP);this.end=Math.min(this.entries.length,this.start+WINDOW_SIZE);this.reading=true;if(this.end<this.entries.length)this.liveHtml='';this.render(anchor);return}
|
|
103
118
|
if(!this.hasMore || this.loading)return
|
|
104
119
|
this.reading=true
|
|
105
120
|
this.pendingOlder=true
|
|
106
121
|
try{await this.options.older()}finally{this.pendingOlder=false}
|
|
107
122
|
}
|
|
108
|
-
latest() {this.reading=false;this.end=this.entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE);this.liveHtml=this.options.live?.()
|
|
109
|
-
|
|
123
|
+
latest() {this.reading=false;this.intentUntil=0;this.end=this.entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE);this.liveHtml=this.options.live?.()??this.pendingLive??'';this.render(null,true)}
|
|
124
|
+
pause() {if(!this.paused)this.savedScroll=this.box.scrollTop;this.paused=true}
|
|
125
|
+
resume() {
|
|
126
|
+
if(!this.paused)return
|
|
127
|
+
this.paused=false;this.box.scrollTop=this.savedScroll||0
|
|
128
|
+
const pending=this.pending;this.pending=null;if(pending)this.set(pending.entries,pending.options)
|
|
129
|
+
}
|
|
130
|
+
reset() {cancelAnimationFrame(this.frame);cancelAnimationFrame(this.releaseFrame);this.frame=0;this.entries=[];this.start=this.end=this.previousLength=0;this.lastRange='';this.nodes.clear();this.reading=false;this.pendingOlder=false;this.suppress=false;this.intentUntil=0;this.pendingLive='';this.pending=null;this.paused=false;this.lastScrollTop=0;this.box.replaceChildren()}
|
|
110
131
|
}
|
|
111
132
|
let cacheEpoch=0
|
|
112
133
|
let database
|