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/public/app.js CHANGED
@@ -75,6 +75,7 @@ const state = {
75
75
  questions: [], // 待处理提问
76
76
  queues: {}, // sessionId -> queue items
77
77
  queueSteering: {}, // sessionId:itemId -> pending steer request
78
+ compactionBootAt: Date.now(),
78
79
  compactions: {}, // sessionId -> {active, phase, startedAt, message, source}
79
80
  pendingCommands: {}, // sessionId -> command name; waits briefly before showing generic progress
80
81
  compactionPollTimer: null,
@@ -124,12 +125,15 @@ for (const key of ['server', 'token']) {
124
125
  state.modelSettings = { status: 'idle', error: '', writable: false, hasDocument: false, providers: [], namespaces: [], credentials: {} }; state.modelEditor = null
125
126
  state.goalEdit = null; state.goalEditContext = null
126
127
  state.approvals = []; state.questions = []; state.questionModal = null
127
- state.queues = {}; state.jobs = {}; state.queueSteering = {}; state.compactions = {}; state.pendingCommands = {}; state.sessionTurnTimes = {}
128
+ state.queues = {}; state.jobs = {}; state.queueSteering = {}; state.compactions = {}; state.compactionTerminals = {}; state.compactionSeqs = {}; state.compactionBootAt = Date.now(); state.pendingCommands = {}; state.sessionTurnTimes = {}
128
129
  state.sessionActivity = new Set(); state.pendingPrompts = new Set()
129
130
  state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
130
131
  state.wb = null; state.wbProjects = []; state.wbArchived = []; state.workspaceFilter = ''; state.fs.workspaceId = ''; clearTimeout(scheduleHistoryCacheSave._t)
131
132
  window.DshPluginCenter?.close()
132
133
  window.DshInsights?.close()
134
+ window.DshExtensions?.close()
135
+ window.DshExtensions?.invalidateCapabilities()
136
+ if (typeof document !== 'undefined') document.getElementById('btn-insights')?.classList.add('hidden')
133
137
  if(typeof document!=='undefined') {
134
138
  const identityGeneration=connectionGeneration
135
139
  queueMicrotask(()=>{if(identityGeneration===connectionGeneration&&typeof startOverviewDetection==='function')startOverviewDetection(true,true)})
@@ -1451,12 +1455,14 @@ function onResume() {
1451
1455
  }
1452
1456
  window.scrollTo(0, 0)
1453
1457
  updateConn()
1458
+ void openPendingNavigation()
1454
1459
  }
1455
1460
 
1456
1461
  /* 回前台 / 定时兜底: 任何流不在 OPEN 就重连; 多服务器时顺便重测速 */
1457
1462
  document.addEventListener('visibilitychange', () => {
1458
1463
  if (document.visibilityState === 'visible') {
1459
1464
  onResume()
1465
+ if (window.NativeBackground?.getPendingNavigation?.()) return
1460
1466
  if (state.servers.length) selectFastestServer({ silent: true })
1461
1467
  else if (state.token) repairMissingStreams()
1462
1468
  }
@@ -1495,22 +1501,27 @@ function onMuxFrame(full) {
1495
1501
  if (f.sessionId === state.current) { applyReasoningBaseline(f.partialReasoning); scheduleReasoningRender() }
1496
1502
  return
1497
1503
  }
1498
- if (f.type === 'session/event') return onSessionEvent(f.sessionId, f.event)
1504
+ if (f.type === 'session/event') return onSessionEvent(f.sessionId, f.event, { replay: f.replay === true })
1499
1505
  if (f.type === 'session/subscribed') return
1500
1506
  if (f.type === 'approval/requested') {
1501
1507
  state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId)
1502
1508
  state.approvals.push({ ...f, rpcId: full.rpcId })
1503
- notify(t('notify.approvalTitle'), t('notify.approvalBody', { tool: f.toolName || t('tool.unknown') }))
1509
+ notifyPendingRequest(full, t('notify.approvalTitle'), t('notify.approvalBody', { tool: f.toolName || t('tool.unknown') }))
1504
1510
  renderPending(); return
1505
1511
  }
1506
- if (f.type === 'approval/resolved') { state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId); renderPending(); return }
1512
+ if (f.type === 'approval/resolved') { clearPendingNotification(f); state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId); renderPending(); return }
1507
1513
  if (f.type === 'question/requested') {
1508
1514
  state.questions = state.questions.filter(q => q.rpcId !== full.rpcId)
1509
1515
  state.questions.push({ ...f, rpcId: full.rpcId })
1510
- notify(t('notify.questionTitle'), f.questions?.map(q => q.question).join(' / ') || t('notify.questionBody'))
1516
+ notifyPendingRequest(full, t('notify.questionTitle'), f.questions?.map(q => q.question).join(' / ') || t('notify.questionBody'))
1517
+ renderPending(); return
1518
+ }
1519
+ if (f.type === 'question/resolved') {
1520
+ clearPendingNotification(f)
1521
+ state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId)
1522
+ if (state.questionModal?.rpcId === f.questionRpcId) { $('modal-question').classList.add('hidden'); state.questionModal = null }
1511
1523
  renderPending(); return
1512
1524
  }
1513
- if (f.type === 'question/resolved') { state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId); renderPending(); return }
1514
1525
  if (f.type === 'session/queue') { state.queues[f.sessionId] = f.items || []; renderQueue(); return }
1515
1526
  if (f.type === 'session/jobs') { state.jobs[f.sessionId] = f.jobs || []; renderJobs(); return }
1516
1527
  if (f.type === 'session/projection') { applyProjection(f.sessionId, f.key, f.value, f.seq); return }
@@ -1552,6 +1563,7 @@ function compactElapsed(startedAt) {
1552
1563
  }
1553
1564
 
1554
1565
  function setCompactionStatus(sessionId, next) {
1566
+ state.compactionTerminals ||= {}
1555
1567
  if (!sessionId) return
1556
1568
  const previous = state.compactions[sessionId]
1557
1569
  const active = next?.active === true
@@ -1563,10 +1575,15 @@ function setCompactionStatus(sessionId, next) {
1563
1575
  startedAt: Number(next.startedAt) || previous?.startedAt || Date.now(),
1564
1576
  message: String(next.message || ''),
1565
1577
  source: next.source || previous?.source || 'event',
1578
+ compactionId: next.compactionId || previous?.compactionId || '',
1579
+ notify: next.notify ?? previous?.notify ?? (next.source === 'command'),
1566
1580
  }
1567
1581
  } else {
1568
1582
  delete state.compactions[sessionId]
1569
1583
  if (previous?.active) {
1584
+ state.compactionTerminals[sessionId] = { startedAt: previous.startedAt, compactionId: previous.compactionId }
1585
+ }
1586
+ if (previous?.active && previous.notify && next?.notify !== false && ['complete', 'failed'].includes(next?.phase)) {
1570
1587
  const command = previous.command || 'compact'
1571
1588
  if (next?.phase === 'failed') toast(command === 'compact'
1572
1589
  ? t('session.compactFailed', { msg: next.message || t('send.failed') })
@@ -1580,18 +1597,25 @@ function setCompactionStatus(sessionId, next) {
1580
1597
 
1581
1598
  async function refreshCompactionStatus(sessionId = state.current) {
1582
1599
  if (!sessionId) return
1600
+ const connection = captureConnection()
1583
1601
  try {
1584
1602
  const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(8000) : undefined
1585
- const url = new URL(apiUrl('/remote/api/command-status'), location.href)
1603
+ const url = new URL(connection.server + '/remote/api/command-status', location.href)
1586
1604
  url.searchParams.set('sessionId', sessionId)
1587
- const res = await fetch(url, { headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }, ...(signal ? { signal } : {}) })
1605
+ const res = await fetch(url, { headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }, ...(signal ? { signal } : {}) })
1606
+ if (!connection.valid()) return
1588
1607
  if (res.status === 401) { authFailure(); return }
1589
1608
  if (!res.ok) return
1609
+ if (!connection.valid()) return
1590
1610
  const body = await res.json().catch(() => null)
1611
+ if (!connection.valid()) return
1591
1612
  const operation = body?.operation || body?.compact
1592
1613
  if (!operation) return
1614
+ if (operation.startedAt && activeCompaction(sessionId)?.startedAt > Number(operation.startedAt)) return
1593
1615
  const pending = state.pendingCommands[sessionId]
1594
- if (operation.active) {
1616
+ if (operation.active === true) {
1617
+ const terminal = state.compactionTerminals?.[sessionId]
1618
+ if (terminal && Number(operation.startedAt) <= terminal.startedAt) return
1595
1619
  delete state.pendingCommands[sessionId]
1596
1620
  setCompactionStatus(sessionId, { ...operation, source: 'status' })
1597
1621
  } else if (activeCompaction(sessionId) && activeCompaction(sessionId).source !== 'event') {
@@ -1625,18 +1649,29 @@ function ensureCompactionMonitoring() {
1625
1649
  }
1626
1650
  }
1627
1651
 
1628
- function observeCompactionEvent(sessionId, event) {
1629
- if (event?.type === 'compaction/start') {
1630
- setCompactionStatus(sessionId, { active: true, phase: 'running', startedAt: activeCompaction(sessionId)?.startedAt || Date.now(), source: activeCompaction(sessionId)?.source || 'event' })
1631
- } else if (event?.type === 'compaction/end' && activeCompaction(sessionId)?.source === 'event') {
1632
- setCompactionStatus(sessionId, { active: false, phase: 'complete' })
1652
+ function observeCompactionEvent(sessionId, event, meta = {}) {
1653
+ if (!event || !sessionId || !['compaction/start','compaction/end','session/end-seed'].includes(event.type)) return
1654
+ state.compactionSeqs ||= {}; state.compactionBootAt ||= Date.now()
1655
+ const seq = Number(event.seq), previous = activeCompaction(sessionId)
1656
+ if (seq > 0 && seq <= (state.compactionSeqs[sessionId] || 0)) return
1657
+ const id = event.data?.compactionId || ''
1658
+ if (event.type === 'compaction/end' && previous?.compactionId && previous.compactionId !== id) return
1659
+ if (seq > 0) state.compactionSeqs[sessionId] = seq
1660
+ const time = typeof event.time === 'number' ? event.time : Date.parse(event.time)
1661
+ if (event.type === 'compaction/start') {
1662
+ setCompactionStatus(sessionId, { active: true, phase: 'running', compactionId: id,
1663
+ startedAt: previous?.startedAt || (Number.isFinite(time) ? time : Date.now()), source: previous?.source || 'event',
1664
+ notify: meta.replay ? false : previous?.notify || Number.isFinite(time) && time >= state.compactionBootAt })
1665
+ } else {
1666
+ setCompactionStatus(sessionId, { active: false, phase: event.type === 'session/end-seed' ? 'interrupted' : event.data?.error ? 'failed' : 'complete',
1667
+ message: event.data?.error || '', ...(meta.replay || event.type === 'session/end-seed' ? { notify: false } : {}) })
1633
1668
  }
1634
1669
  }
1635
1670
 
1636
- function onSessionEvent(sessionId, event) {
1671
+ function onSessionEvent(sessionId, event, meta = {}) {
1637
1672
  if (!event) return
1638
1673
  const s = state.byId.get(sessionId)
1639
- observeCompactionEvent(sessionId, event)
1674
+ observeCompactionEvent(sessionId, event, meta)
1640
1675
  if (event.type === 'turn/start' || event.type === 'turn/end') {
1641
1676
  noteSessionTurnTime(sessionId, event)
1642
1677
  renderSessions()
@@ -1707,9 +1742,37 @@ function removeLocalSessionRecord(sessionId) {
1707
1742
  }
1708
1743
 
1709
1744
  function proj(s, key, d) { return s?.projections?.values?.[key] ?? d }
1710
- function openInsights(tab = 'context') {
1711
- window.DshInsights?.open({ tab, connection: captureConnection(), url: apiUrl,
1712
- getSession: () => state.byId.get(state.current), getTitle: () => sessionTitleValue(state.byId.get(state.current)) })
1745
+ function optionalPluginConfig(connection = captureConnection()) {
1746
+ return { connection, valid: connection.valid, url: path => connection.server + path,
1747
+ headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() } }
1748
+ }
1749
+ function availableInsightTabs(capabilities, session) {
1750
+ const context = capabilities.context
1751
+ return [...(context ? ['context'] : []), ...(capabilities.cost ? ['cost'] : [])]
1752
+ }
1753
+ async function refreshInsightEntry() {
1754
+ const control = $('btn-insights'), id = state.current, connection = captureConnection()
1755
+ if (!control || !id || !connection.token || !window.DshExtensions) { control?.classList.add('hidden'); return }
1756
+ const capabilities = await window.DshExtensions.getCapabilities(optionalPluginConfig(connection))
1757
+ if (!connection.valid() || state.current !== id) return
1758
+ const tabs = availableInsightTabs(capabilities, state.byId.get(id))
1759
+ control.classList.toggle('hidden', !tabs.length)
1760
+ const label = t(tabs.length === 2 ? 'insights.title' : tabs[0] === 'cost' ? 'insights.costTitle' : 'insights.contextTitle')
1761
+ control.textContent = label; control.title = label; control.setAttribute('aria-label', label)
1762
+ }
1763
+ async function openInsights(tab = 'context', fullPage = false) {
1764
+ const connection = captureConnection(), id = state.current
1765
+ const capabilities = await window.DshExtensions.getCapabilities(optionalPluginConfig(connection))
1766
+ if (!connection.valid() || state.current !== id || !id) return
1767
+ const allowedTabs = availableInsightTabs(capabilities, state.byId.get(id))
1768
+ if (!allowedTabs.length) { void refreshInsightEntry(); return }
1769
+ window.DshInsights?.close()
1770
+ const view = fullPage ? getConversationView() : null, wasPaused = view?.paused
1771
+ view?.pause()
1772
+ window.DshInsights?.open({ tab, fullPage, allowedTabs, connection, url: path => connection.server + path,
1773
+ getSession: () => state.byId.get(state.current), getTitle: () => sessionTitleValue(state.byId.get(state.current)),
1774
+ onFullPage: selected => void openInsights(selected, true),
1775
+ onClose: () => { if (view && !wasPaused && connection.valid() && state.current === id) view.resume() } })
1713
1776
  }
1714
1777
  function hydrateSessionProjections(sessionId, projections) {
1715
1778
  const s = state.byId.get(sessionId)
@@ -2472,9 +2535,7 @@ function scheduleReasoningRender() {
2472
2535
  reasoningRenderTimer = setTimeout(() => {
2473
2536
  reasoningRenderTimer = null
2474
2537
  if (!state.current) return
2475
- const box = $('history')
2476
- const nearBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 240
2477
- renderHistory(false, nearBottom ? 'bottom' : 'fixed')
2538
+ renderHistory(false, 'fixed')
2478
2539
  }, 80)
2479
2540
  }
2480
2541
 
@@ -2503,7 +2564,7 @@ function getConversationView() {
2503
2564
  if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
2504
2565
  html:entry=>eventHtml(entry, {toolNames:state.history.toolNames}),
2505
2566
  older:()=>loadHistory(false),olderLabel:()=>t('history.earlier'),loadingLabel:()=>t('history.loadingEarlier'),live:partialReasoningHtml,
2506
- changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end;$('btn-history-latest')?.classList.toggle('hidden',!view.reading&&view.end>=view.entries.length&&!state.history.tailEvicted);updateRail(view.domChanged)},
2567
+ changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end;$('btn-history-latest')?.classList.toggle('hidden',!view.reading&&view.end>=view.entries.length&&!state.history.tailEvicted);const latest=$('btn-history-latest');if(latest)latest.textContent=t('history.latest')+(view.unread?' ('+view.unread+')':view.hasPending?' · '+(I18N.lang==='en'?'New content':'有新内容'):'');updateRail(view.domChanged)},
2507
2568
  scrolled:()=>{updateRail()}
2508
2569
  })
2509
2570
  return conversationView
@@ -2756,8 +2817,8 @@ function blockHtml(b) {
2756
2817
  if (!b || typeof b !== 'object') return `<p>${esc(String(b))}</p>`
2757
2818
  if ((b.type === 'tool-call' || b.type === 'tool-result') && LS.get('showTools', '1') === '0') return ''
2758
2819
  switch (b.type) {
2759
- case 'text': return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '') : esc(b.text ?? '')}</div>`
2760
- case 'file': return `<div class="tool">📎 ${esc(b.attachment?.name || b.name || 'file')} <small>${esc(b.attachment?.bytes ?? b.bytes ?? '')} bytes</small></div>`
2820
+ case 'text': return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true }) : esc(b.text ?? '')}</div>`
2821
+ case 'file': if (typeof window !== 'undefined' && window.DshChatFiles) return window.DshChatFiles.render(b); return `<div class="tool">📎 ${esc(b.attachment?.name || b.name || 'file')} <small>${esc(b.attachment?.bytes ?? b.bytes ?? '')} bytes</small></div>`
2761
2822
  case 'image': return `<img alt="${t('block.image')}" src="data:${esc(b.mediaType || 'image/png')};base64,${esc(b.data || '')}">`
2762
2823
  case 'thinking':
2763
2824
  case 'reasoning':
@@ -2812,6 +2873,7 @@ let sessionCardsRenderGeneration = 0
2812
2873
  async function renderSessionCards() {
2813
2874
  const connection = captureConnection()
2814
2875
  window.DshInsights?.update()
2876
+ void refreshInsightEntry()
2815
2877
  const renderGeneration = ++sessionCardsRenderGeneration
2816
2878
  const sessionId = state.current
2817
2879
  const s = state.byId.get(sessionId)
@@ -3850,16 +3912,16 @@ function renderSessionPending() {
3850
3912
  <div class="pc-desc">${esc(approvalDetail(item))}</div>
3851
3913
  <div class="goal-actions"><button type="button" class="mini-btn" data-session-approve="1">${t('pending.allow')}</button><button type="button" class="mini-btn" data-session-approve="0">${t('pending.reject')}</button></div>
3852
3914
  </article>`
3853
- return `<article class="pending-card question" data-session-question="${esc(item.rpcId)}">
3854
- <div class="pc-title">❓ ${esc((item.questions || []).map(question => question.question).filter(Boolean).join(' / ') || t('notify.questionTitle'))}</div>
3855
- <div class="goal-actions"><button type="button" class="mini-btn" data-session-answer>${t('pending.answer')}</button></div>
3856
- </article>`
3915
+ return `<button type="button" class="pending-card question" data-session-question="${esc(item.rpcId)}" aria-haspopup="dialog">
3916
+ <span class="question-card-head"><span class="pc-title">❓ ${esc(item.questions?.[0]?.header || t('notify.questionTitle'))}</span><span class="mini-btn">${t('pending.answer')}</span></span>
3917
+ <span class="question-summary">${esc(questionSummary(item))}</span>
3918
+ </button>`
3857
3919
  }).join('')}</div>`
3858
3920
  box.querySelectorAll('[data-session-approve]').forEach(button => {
3859
3921
  button.addEventListener('click', () => approveApproval(button.closest('[data-session-approval]')?.dataset.sessionApproval || '', button.dataset.sessionApprove === '1'))
3860
3922
  })
3861
- box.querySelectorAll('[data-session-answer]').forEach(button => {
3862
- button.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === button.closest('[data-session-question]')?.dataset.sessionQuestion)))
3923
+ box.querySelectorAll('[data-session-question]').forEach(button => {
3924
+ button.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === button.dataset.sessionQuestion)))
3863
3925
  })
3864
3926
  }
3865
3927
 
@@ -3878,21 +3940,42 @@ async function approveApproval(id, allow) {
3878
3940
  }
3879
3941
  if (!connection.valid()) return
3880
3942
  toast(ok ? (allow ? t('pending.allowed') : t('pending.rejected')) : t('pending.stale'), ok ? 'ok' : 'err')
3943
+ if (ok) clearPendingNotification({ type: 'approval/resolved', approvalId: a.approvalId })
3881
3944
  state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
3882
3945
  renderPending()
3883
3946
  }
3884
3947
 
3948
+ function questionSummary(q) {
3949
+ return (q.questions || []).map(item => String(item.question || '').replace(/\[([^\]]+)\]\([^)]+\)/g, '$1').replace(/[*_`#>]/g, '')).join(' / ').replace(/\s+/g, ' ').trim().slice(0, 240)
3950
+ }
3951
+
3952
+ function questionMarkup(item) {
3953
+ const text = String(item.question || '')
3954
+ return (item.header ? `<strong>${esc(item.header)}</strong>` : '') + (window.mdToHtml ? window.mdToHtml(text, { richContent: false, fileLinks: true }) : esc(text))
3955
+ }
3956
+
3957
+ function fitQuestionViewport() {
3958
+ const viewport = window.visualViewport
3959
+ const modal = $('modal-question')
3960
+ if (!modal || !viewport) return
3961
+ modal.style.top = viewport.offsetTop + 'px'
3962
+ modal.style.height = viewport.height + 'px'
3963
+ modal.style.bottom = 'auto'
3964
+ }
3965
+
3885
3966
  function openQuestionModal(q) {
3886
3967
  if (!q) return
3887
3968
  state.questionModal = q
3888
3969
  $('question-body').innerHTML = q.questions.map((item, i) => `
3889
3970
  <div class="q-item">
3890
- <div class="q-text">${esc(item.header ? item.header + ':' : '')}${esc(item.question)}</div>
3971
+ <div class="q-text md">${questionMarkup(item)}</div>
3891
3972
  ${(item.options || []).map((o, j) => `
3892
3973
  <label class="q-option"><input type="${item.multiSelect ? 'checkbox' : 'radio'}" name="q${i}" value="${esc(o.label)}" data-q="${i}"><span>${esc(o.label)}${o.description ? `<div class="muted">${esc(o.description)}</div>` : ''}</span></label>`).join('')}
3893
3974
  <textarea rows="2" placeholder="${t('question.customPlaceholder')}" data-qcustom="${i}"></textarea>
3894
3975
  </div>`).join('')
3895
3976
  $('modal-question').classList.remove('hidden')
3977
+ $('question-body').scrollTop = 0
3978
+ fitQuestionViewport()
3896
3979
  }
3897
3980
 
3898
3981
  async function submitQuestion() {
@@ -3919,6 +4002,7 @@ async function submitQuestion() {
3919
4002
  }
3920
4003
  if (!connection.valid()) return
3921
4004
  if (ok) {
4005
+ clearPendingNotification({ type: 'question/resolved', questionRpcId: q.rpcId })
3922
4006
  toast(t('question.submitted'), 'ok')
3923
4007
  if (state.questionModal === q) { $('modal-question').classList.add('hidden'); state.questionModal = null }
3924
4008
  state.questions = state.questions.filter(x => x.rpcId !== q.rpcId)
@@ -4121,7 +4205,6 @@ async function createWorkspace() {
4121
4205
  button.disabled = true
4122
4206
  try {
4123
4207
  const res = await fetch(fsApiUrl('/mkdir', { path: parent, name }), { method: 'POST', headers: fsHeaders() })
4124
- if (!connection.valid()) return
4125
4208
  if (res.status === 401) { fsAuthError(401); return }
4126
4209
  const data = await res.json().catch(() => ({}))
4127
4210
  if (!connection.valid()) return
@@ -5388,6 +5471,56 @@ async function downloadUpdate() {
5388
5471
 
5389
5472
  /* ---------------- 通知 ---------------- */
5390
5473
  const CAP = window.Capacitor || null
5474
+ const pendingNotificationSeen = new Set()
5475
+ function notifyPendingRequest(full, title, body) {
5476
+ const bridge = window.NativeBackground
5477
+ if (bridge?.handlePendingEvent) {
5478
+ bridge.handlePendingEvent(bgBase(), state.token || '', JSON.stringify(full), LS.get('notify', '0') === '1')
5479
+ return
5480
+ }
5481
+ const key = connectionGeneration + ':' + (full.payload?.approvalId || full.rpcId)
5482
+ if (LS.get('notify', '0') !== '1' || pendingNotificationSeen.has(key)) return
5483
+ if (pendingNotificationSeen.size >= 512) pendingNotificationSeen.delete(pendingNotificationSeen.values().next().value)
5484
+ pendingNotificationSeen.add(key)
5485
+ notify(title, body)
5486
+ }
5487
+ function clearPendingNotification(payload) {
5488
+ window.NativeBackground?.handlePendingEvent?.(bgBase(), state.token || '', JSON.stringify({ payload }), false)
5489
+ }
5490
+
5491
+ let pendingNavigationBusy = false, pendingNavigationReady = false
5492
+ async function openPendingNavigation() {
5493
+ const bridge = window.NativeBackground
5494
+ if (!pendingNavigationReady || pendingNavigationBusy || !bridge?.getPendingNavigation) return
5495
+ const raw = bridge.getPendingNavigation()
5496
+ if (!raw) return
5497
+ pendingNavigationBusy = true
5498
+ try {
5499
+ const target = JSON.parse(raw)
5500
+ const matches = (base, token) => bridge.matchesPendingNavigation(base, token, target.identity)
5501
+ if (!matches(bgBase(), state.token || '')) {
5502
+ const server = state.servers.find(s => matches(s.url, serverToken(s)))
5503
+ if (!server) { toast(t('notify.hostUnavailable'), 'err'); bridge.acknowledgePendingNavigation(raw); return }
5504
+ state.activeGroup = server.group
5505
+ state.groupActive[server.group] = server.id
5506
+ state.server = server.url; state.token = serverToken(server)
5507
+ LS.set('token', state.token)
5508
+ saveServers(); syncBgConfig(); renderServers(); openStreams()
5509
+ }
5510
+ bridge.acknowledgePendingNavigation(raw)
5511
+ const connection = captureConnection()
5512
+ await refreshSessions()
5513
+ if (!connection.valid()) return
5514
+ if (state.byId.has(target.sessionId)) await openSession(target.sessionId)
5515
+ else { showView('view-activity'); toast(t('question.stale'), 'err') }
5516
+ } catch (error) { toast(error.message, 'err') }
5517
+ finally {
5518
+ pendingNavigationBusy = false
5519
+ const next = bridge.getPendingNavigation()
5520
+ if (next && next !== raw) void openPendingNavigation()
5521
+ }
5522
+ }
5523
+ window.addEventListener('dsh-pending-navigation', () => void openPendingNavigation())
5391
5524
  async function ensureNotify() {
5392
5525
  // App 内走原生通知插件(WebView 的 Web Notification 在 MIUI 拿不到权限)
5393
5526
  if (CAP?.isNativePlatform?.()) {
@@ -6156,10 +6289,12 @@ async function openModelConfigDocument() {
6156
6289
  }
6157
6290
  /* ---------------- 视图切换 ---------------- */
6158
6291
  function showView(id) {
6292
+ if (id !== 'view-session') conversationView?.pause()
6159
6293
  if (id !== 'view-session' && document.body.classList.contains('in-session') && state.current) void archiveEmptySessionOnLeave(state.current)
6160
6294
  for (const v of ['view-home', 'view-files', 'view-session', 'view-activity', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
6161
6295
  // 离开会话页必须清掉 in-session, 否则其他页面顶栏被 body 样式隐藏
6162
6296
  document.body.classList.toggle('in-session', id === 'view-session')
6297
+ if (id === 'view-session') conversationView?.resume()
6163
6298
  $('session-actions')?.close()
6164
6299
  $('session-info')?.close()
6165
6300
  document.querySelectorAll('.nav-btn').forEach(b => b.classList.toggle('active', b.dataset.view === id))
@@ -6172,7 +6307,7 @@ function showView(id) {
6172
6307
  loadFs(workspace?.path || null, { silent: true, resetRoot: true })
6173
6308
  }
6174
6309
  if (id === 'view-plugins') openPluginPage()
6175
- else window.DshPluginCenter?.close()
6310
+ else window.DshExtensions?.close()
6176
6311
  if (id === 'view-settings') showSettingsHome()
6177
6312
  if(id==='view-activity')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}
6178
6313
  }
@@ -7211,6 +7346,8 @@ function bindUi() {
7211
7346
  // 提问
7212
7347
  $('question-submit').addEventListener('click', submitQuestion)
7213
7348
  $('question-later').addEventListener('click', () => $('modal-question').classList.add('hidden'))
7349
+ window.visualViewport?.addEventListener('resize', fitQuestionViewport)
7350
+ window.visualViewport?.addEventListener('scroll', fitQuestionViewport)
7214
7351
  // goal
7215
7352
  $('goal-close').addEventListener('click', () => $('modal-goal').classList.add('hidden'))
7216
7353
  $('goal-edit').addEventListener('click', submitGoalEdit)
@@ -7331,12 +7468,14 @@ function bindUi() {
7331
7468
  toast(t(action === 'send' ? 'settings.mobileEnterSend' : 'settings.mobileEnterNewline'), 'ok')
7332
7469
  })
7333
7470
  $('opt-notify').checked = LS.get('notify', '0') === '1'
7471
+ window.NativeBackground?.setPendingNotificationsEnabled?.($('opt-notify').checked)
7334
7472
  $('opt-notify').addEventListener('change', async (e) => {
7335
7473
  if (e.target.checked) {
7336
7474
  const ok = await ensureNotify()
7337
7475
  if (!ok) { e.target.checked = false; return toast(t('settings.notifyDenied')) }
7338
7476
  }
7339
7477
  LS.set('notify', e.target.checked ? '1' : '0')
7478
+ window.NativeBackground?.setPendingNotificationsEnabled?.(e.target.checked)
7340
7479
  })
7341
7480
  $('opt-peak-remind').checked = peakRemindOn()
7342
7481
  $('opt-peak-remind').addEventListener('change', async (e) => {
@@ -7419,6 +7558,11 @@ function bindUi() {
7419
7558
 
7420
7559
  bindRail()
7421
7560
 
7561
+ for (const id of ['history', 'question-body']) window.DshChatFiles?.bind($(id), () => {
7562
+ const c=captureConnection(),sessionId=id==='history'?state.current:state.questionModal?.sessionId
7563
+ return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:!!CAP?.isNativePlatform?.(),headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,
7564
+ valid:()=>c.valid()&&sessionId===(id==='history'?state.current:state.questionModal?.sessionId) }
7565
+ })
7422
7566
  initCustomSelects()
7423
7567
 
7424
7568
  $('btn-history-latest').addEventListener('click',()=>{getConversationView().latest();if(state.history.tailEvicted)void loadHistory(true)})
@@ -7431,11 +7575,14 @@ function applyNativeInsets() {
7431
7575
  const raw = window.NativeUpdate?.getInsets?.()
7432
7576
  if (!raw) return
7433
7577
  const ins = JSON.parse(raw)
7578
+ if (ins.mode === 'overlap') document.documentElement.dataset.nativeInsets = 'overlap'
7434
7579
  document.documentElement.style.setProperty('--native-top', (ins.top || 0) + 'px')
7435
7580
  document.documentElement.style.setProperty('--native-bottom', (ins.bottom || 0) + 'px')
7436
7581
  } catch {}
7437
7582
  }
7438
7583
 
7584
+ window.addEventListener('dsh-native-insets', applyNativeInsets)
7585
+
7439
7586
  async function boot() {
7440
7587
  initToken()
7441
7588
  bindUi()
@@ -7465,19 +7612,24 @@ async function boot() {
7465
7612
  startAnnouncementPolling()
7466
7613
  scheduleStartupNotices()
7467
7614
  renderPending()
7615
+ pendingNavigationReady = true
7616
+ void openPendingNavigation()
7468
7617
  }
7469
7618
 
7470
7619
  document.addEventListener('DOMContentLoaded', boot)
7471
7620
 
7472
- function openPluginPage() {
7621
+ function openPluginPage(route = 'manage') {
7473
7622
  const connection = captureConnection()
7474
7623
  if (!connection.token) {
7475
7624
  $('plugin-page').textContent = '请先在设置中连接 DSH 主机。'
7476
7625
  return
7477
7626
  }
7478
- window.DshPluginCenter.mount({
7627
+ window.DshExtensions.mount({
7628
+ connection, getSession: () => state.byId.get(state.current), getTitle: () => sessionTitleValue(state.byId.get(state.current)),
7629
+ openContext: () => void openInsights('context', true),
7630
+ returnToSession: () => showView('view-session'), scrollTop: () => window.scrollTo(0,0),
7479
7631
  url: path => connection.server + path,
7480
7632
  headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
7481
7633
  valid: connection.valid,
7482
- }, $('plugin-page'))
7634
+ }, $('plugin-page'), route)
7483
7635
  }
@@ -0,0 +1,85 @@
1
+ /* Explicit user downloads only; attachment IDs never become filesystem paths. */
2
+ (function(root,factory){const api=factory(root);if(typeof module==='object')module.exports=api;root.DshChatFiles=api})(typeof window!=='undefined'?window:globalThis,(root)=>{
3
+ const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))
4
+ function relativePath(path) {
5
+ return typeof path==='string' && !!path && path.length<=4096 && !/[\x00-\x1f]/.test(path) && !/^(?:[a-z][a-z0-9+.-]*:|[\\/]|#|\?)/i.test(path)
6
+ && !/^[a-f0-9]{64}$/i.test(path) && !/[?#]/.test(path)
7
+ && (/^\.{1,2}[\\/]/.test(path) || /(?:^|[\\/])[^\\/]+\.[^\\/.]+$/.test(path))
8
+ }
9
+ function pathOf(value,cwd='') {
10
+ if(typeof value!=='string'||value.length>4096||/[\x00-\x1f]/.test(value))return ''
11
+ let path=value.trim()
12
+ if(/^file:/i.test(path)){try{const u=new URL(path);if(u.hostname&&u.hostname!=='localhost')return '';path=decodeURIComponent(u.pathname);if(/^\/[a-z]:\//i.test(path))path=path.slice(1)}catch{return ''}}
13
+ if(/[\x00-\x1f]/.test(path))return ''
14
+ if(/^(?:[a-z]:[\\/]|\/(?!\/))/i.test(path))return path
15
+ if(relativePath(path)){const base=pathOf(cwd);if(base)return base.replace(/[\\/]+$/,'')+'/'+path}
16
+ return ''
17
+ }
18
+
19
+ function render(block) {
20
+ const a=block.attachment||block,raw=a.path||block.path||''
21
+ const path=pathOf(raw)||(relativePath(raw)?raw:''),id=/^[a-f0-9]{64}$/.test(a.attachmentId||'')?a.attachmentId:''
22
+ const name=a.name||block.name||'file'
23
+ return `<div class="chat-file"><span class="chat-file-name">📎 ${esc(name)} <small>${esc(a.bytes??block.bytes??'')} bytes</small></span>${id||path?`<button type="button" ${id?'data-dsh-attachment="'+esc(id)+'"':''} ${path?'data-dsh-file-path="'+esc(path)+'"':''} data-dsh-file-name="${esc(name)}">下载文件</button>`:''}</div>`
24
+ }
25
+ async function trackDownload(id,control,c) {
26
+ // New shells expose DownloadManager state; older shells keep their enqueue-only contract.
27
+ for (;;) {
28
+ await new Promise(resolve=>setTimeout(resolve,1000))
29
+ if(!c.valid() || control.isConnected===false)return
30
+ const status=JSON.parse(root.NativeFile.getFileDownloadStatus(String(id))||'{}')
31
+ if(status.phase==='complete'){
32
+ control.textContent='下载完成 · 再次下载'
33
+ c.notice('下载完成:下载/dsh-remote/'+status.name,'ok');return
34
+ }
35
+ if(status.phase==='error')throw Error(status.error||'下载失败,请重试')
36
+ if(status.phase==='unknown')throw Error('系统下载任务已移除,请重试')
37
+ control.textContent=status.phase==='paused'?'下载暂停,等待网络…':'下载中…'
38
+ }
39
+ }
40
+ function bind(target,config){target.addEventListener('click',async event=>{
41
+ const control=event.target.closest?.('[data-dsh-file-path],[data-dsh-attachment]')
42
+ if(!control||!target.contains(control)||control.getAttribute('aria-busy')==='true')return
43
+ event.preventDefault()
44
+ const c=config(),id=control.dataset.dshAttachment,path=pathOf(control.dataset.dshFilePath,c.cwd)
45
+ if(!c.valid())return
46
+ if(!id&&!path){c.notice('无法定位文件,请核对当前会话的工作目录','err');return}
47
+ const name=(control.dataset.dshFileName||path.split(/[\\/]/).pop()||'download').replace(/[\\/\x00-\x1f]/g,'_')
48
+ const makeUrl=attachment=>{
49
+ const url=new URL(c.server+(attachment?'/remote/api/session-file':'/fs/file'),root.location?.href)
50
+ if(attachment){url.searchParams.set('sessionId',c.sessionId);url.searchParams.set('attachmentId',id)}
51
+ else url.searchParams.set('path',path)
52
+ return url
53
+ }
54
+ const head=url=>fetch(url,{method:'HEAD',redirect:'error',headers:c.headers,signal:AbortSignal.timeout(15000)})
55
+ const original=control.textContent
56
+ control.setAttribute('aria-busy','true')
57
+ try{
58
+ let url=makeUrl(!!id),response=await head(url)
59
+ if(!c.valid())return
60
+ // Only an explicit host path can back up an unsupported attachment endpoint.
61
+ if(id&&path&&[404,405,501,503].includes(response.status)){
62
+ url=makeUrl(false);response=await head(url);if(!c.valid())return
63
+ }
64
+ if(!response.ok)throw Error(response.status===403?'主机不允许下载这个文件':response.status===404?'文件不存在或不属于当前会话':[405,501,503].includes(response.status)?'主机版本暂不支持附件下载,请更新主机插件':'文件下载失败(HTTP '+response.status+')')
65
+ if(c.native){
66
+ if(!root.NativeFile?.downloadToDownloads)throw Error('当前 App 不支持系统下载,请更新 App')
67
+ const task=root.NativeFile.downloadToDownloads(url.href,name,c.token)
68
+ if(root.NativeFile.getFileDownloadStatus&&!task)throw Error('系统下载未能启动,请重试')
69
+ c.notice('已交给系统下载,请在下载目录查看','ok')
70
+ if(root.NativeFile.getFileDownloadStatus&&task){
71
+ control.textContent='下载中…'
72
+ await trackDownload(task,control,c)
73
+ }
74
+ }else{
75
+ if(c.token)url.searchParams.set('token',c.token)
76
+ const link=document.createElement('a');link.href=url.href;link.download=name;link.referrerPolicy='no-referrer'
77
+ document.body.append(link);link.click();link.remove()
78
+ c.notice('已交给浏览器下载,请在下载目录查看','ok')
79
+ }
80
+ }catch(error){
81
+ if(c.valid()){control.textContent=original;c.notice(error.message,'err')}
82
+ }finally{control.removeAttribute('aria-busy')}
83
+ })}
84
+ return {pathOf,relativePath,render,bind}
85
+ })
@@ -297,9 +297,16 @@ button.ds-overview-attention-item, button.ds-overview-session-item { cursor:poin
297
297
  .ds-presets-guide { padding: 2px 8px 10px; font-size: 11px; line-height: 1.5; }
298
298
  .ds-session-cards { flex: none; max-height: 220px; overflow-y: auto; padding: 10px 22px 0; display: flex; flex-direction: column; gap: 8px; }
299
299
  .ds-session-cards:empty { display: none; }
300
- .ds-session-pending { flex:none; margin:10px 22px 0; padding:10px; border:1px solid var(--dsr-warning-line); border-radius:13px; background:var(--dsr-warning-soft); }
300
+ .ds-session-pending { flex:0 1 auto; min-height:0; max-height:30vh; max-height:30dvh; display:flex; flex-direction:column; margin:10px 22px 0; padding:10px; border:1px solid var(--dsr-warning-line); border-radius:13px; background:var(--dsr-warning-soft); }
301
301
  .ds-session-pending-head { display:flex; align-items:center; justify-content:space-between; gap:8px; margin-bottom:8px; color:var(--dsr-text); font-size:12px; font-weight:750; }
302
- .ds-session-pending-list { display:flex; flex-direction:column; gap:8px; }
302
+ .ds-session-pending-head { flex:none; }
303
+ .ds-session-pending-list { min-height:0; overflow-y:auto; overscroll-behavior:contain; display:flex; flex-direction:column; gap:8px; }
304
+ .ds-session-pending-list > * { flex:none; }
305
+ .ds-session-pending button.question { width:100%; text-align:left; color:inherit; cursor:pointer; font:inherit; }
306
+ .ds-question-card-head { display:flex; align-items:center; justify-content:space-between; gap:10px; margin-bottom:5px; }
307
+ .ds-question-card-head .ds-notif-head { min-width:0; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
308
+ .ds-question-card-head .ds-btn { flex:none; white-space:nowrap; }
309
+ .ds-question-summary { display:-webkit-box; -webkit-line-clamp:3; -webkit-box-orient:vertical; overflow:hidden; overflow-wrap:anywhere; font-size:13px; line-height:1.45; color:var(--dsr-muted); }
303
310
  .ds-session-pending .ds-notif-card { min-width:0; box-shadow:none; animation:none; }
304
311
  .ds-session-pending .ds-notif-title, .ds-session-pending .ds-notif-body { overflow-wrap:anywhere; word-break:break-word; }
305
312
  .ds-card { background: var(--dsr-panel); border: 1px solid var(--dsr-line); border-radius: 12px; padding: 10px 12px; }
@@ -536,6 +543,13 @@ button.ds-overview-attention-item, button.ds-overview-session-item { cursor:poin
536
543
  .ds-new-session-name { font-size: 13px; font-weight: 600; }
537
544
  .ds-new-session-path { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dsr-muted); font-size: 11.5px; }
538
545
  .ds-modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 12px; }
546
+ #modal-question .ds-modal-card { box-sizing:border-box; display:flex; flex-direction:column; min-height:0; max-height:calc(100dvh - 32px); overflow:hidden; }
547
+ #modal-question .ds-modal-title, #modal-question .ds-modal-actions { flex:none; }
548
+ #question-body { min-height:0; max-height:none; overscroll-behavior:contain; overflow-wrap:anywhere; }
549
+ #question-body > * { flex:none; }
550
+ #question-body .ds-q-option { min-height:36px; cursor:pointer; }
551
+ #question-body .ds-q-option > span { min-width:0; }
552
+ #question-body pre { white-space:pre-wrap; overflow-wrap:anywhere; }
539
553
  .ds-q-item { border: 1px solid var(--dsr-line); border-radius: 10px; padding: 9px 11px; }
540
554
  .ds-q-text { font-size: 13.5px; margin-bottom: 6px; }
541
555
  .ds-q-option { display: flex; gap: 7px; align-items: flex-start; font-size: 13px; padding: 3px 0; }
@@ -746,3 +760,8 @@ input:focus-visible, select:focus-visible, textarea:focus-visible {
746
760
  }
747
761
 
748
762
  @media(max-width:600px) { .ds-system-pulse-ring { width:108px; height:108px; } .ds-overview-status { font-size:20px; } html[lang="en"] .ds-overview-status { min-block-size:2.5em; } }
763
+ #view-plugins{overflow-y:auto}
764
+
765
+ .chat-file { display:flex; flex-wrap:wrap; align-items:center; gap:8px 12px; padding:12px; border:1px solid var(--dsr-line); border-radius:12px; margin:8px 0; }
766
+ .chat-file-name { min-width:0; flex:1; overflow-wrap:break-word; }.chat-file small { color:var(--dsr-muted); }
767
+ .chat-file button { flex-shrink:0; min-height:44px; padding:8px 12px; border:1px solid var(--dsr-accent-line); border-radius:10px; color:var(--dsr-accent-strong); background:var(--dsr-accent-soft); font:inherit; cursor:pointer; }