dsh-remote-plugin 0.7.5 → 0.8.0-rc.2

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
@@ -513,7 +513,10 @@ async function rpc(method, payload = {}, timeoutMs = 45000) {
513
513
  if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
514
514
  opts.signal = AbortSignal.timeout(timeoutMs)
515
515
  }
516
- const res = await fetch(apiUrl('/api/' + method), opts)
516
+ const operation = window.DshOperations?.supports(method) && activeGatewayCapability('operations') === true
517
+ const connection = operation ? captureConnection() : null
518
+ const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
519
+ const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
517
520
  if (res.status === 401) throw new Error('AUTH')
518
521
  if (!res.ok) throw new Error('HTTP ' + res.status)
519
522
  const full = await res.json()
@@ -1402,7 +1405,7 @@ async function pollKind(kind, cancellation) {
1402
1405
  const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
1403
1406
  const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1404
1407
  const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }
1405
- res = signal ? await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000`), { signal, headers }) : await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000`), { headers })
1408
+ res = await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000&epoch=${encodeURIComponent(cursors[kind + "Epoch"] || "")}`), { ...(signal ? { signal } : {}), headers })
1406
1409
  } catch { return }
1407
1410
  if (!valid()) return
1408
1411
  if (res.status === 401) { authFailure(); return }
@@ -1413,7 +1416,7 @@ async function pollKind(kind, cancellation) {
1413
1416
  if (!data || !Array.isArray(data.events)) return
1414
1417
  // 网关重启或客户端离线过久后,游标可能落后于内存环形缓冲;
1415
1418
  // 从当前缓冲重新接收,并刷新权威会话列表,避免静默漏事件。
1416
- const reset = data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
1419
+ const reset = data.reset === true || (!!data.epoch && !!cursors[kind + 'Epoch'] && cursors[kind + 'Epoch'] !== data.epoch) || data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
1417
1420
  if (reset) {
1418
1421
  state.pollSeq[kind] = 0
1419
1422
  if (kind === 'mux') {
@@ -1424,6 +1427,8 @@ async function pollKind(kind, cancellation) {
1424
1427
  scheduleRefresh()
1425
1428
  if (state.current) void resyncCurrentSession()
1426
1429
  }
1430
+ if (data.epoch) cursors[kind + 'Epoch'] = data.epoch
1431
+ for (const frame of data.baseline || []) { if (kind === 'mux') onMuxFrame(frame); else onHostFrame(frame) }
1427
1432
  for (const item of data.events) {
1428
1433
  if (item.seq > (state.pollSeq[kind] || 0)) {
1429
1434
  state.pollSeq[kind] = item.seq
@@ -1455,12 +1460,14 @@ function onResume() {
1455
1460
  }
1456
1461
  window.scrollTo(0, 0)
1457
1462
  updateConn()
1463
+ void openPendingNavigation()
1458
1464
  }
1459
1465
 
1460
1466
  /* 回前台 / 定时兜底: 任何流不在 OPEN 就重连; 多服务器时顺便重测速 */
1461
1467
  document.addEventListener('visibilitychange', () => {
1462
1468
  if (document.visibilityState === 'visible') {
1463
1469
  onResume()
1470
+ if (window.NativeBackground?.getPendingNavigation?.()) return
1464
1471
  if (state.servers.length) selectFastestServer({ silent: true })
1465
1472
  else if (state.token) repairMissingStreams()
1466
1473
  }
@@ -1504,17 +1511,22 @@ function onMuxFrame(full) {
1504
1511
  if (f.type === 'approval/requested') {
1505
1512
  state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId)
1506
1513
  state.approvals.push({ ...f, rpcId: full.rpcId })
1507
- notify(t('notify.approvalTitle'), t('notify.approvalBody', { tool: f.toolName || t('tool.unknown') }))
1514
+ notifyPendingRequest(full, t('notify.approvalTitle'), t('notify.approvalBody', { tool: f.toolName || t('tool.unknown') }))
1508
1515
  renderPending(); return
1509
1516
  }
1510
- if (f.type === 'approval/resolved') { state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId); renderPending(); return }
1517
+ if (f.type === 'approval/resolved') { clearPendingNotification(f); state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId); renderPending(); return }
1511
1518
  if (f.type === 'question/requested') {
1512
1519
  state.questions = state.questions.filter(q => q.rpcId !== full.rpcId)
1513
1520
  state.questions.push({ ...f, rpcId: full.rpcId })
1514
- notify(t('notify.questionTitle'), f.questions?.map(q => q.question).join(' / ') || t('notify.questionBody'))
1521
+ notifyPendingRequest(full, t('notify.questionTitle'), f.questions?.map(q => q.question).join(' / ') || t('notify.questionBody'))
1522
+ renderPending(); return
1523
+ }
1524
+ if (f.type === 'question/resolved') {
1525
+ clearPendingNotification(f)
1526
+ state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId)
1527
+ if (state.questionModal?.rpcId === f.questionRpcId) { $('modal-question').classList.add('hidden'); state.questionModal = null }
1515
1528
  renderPending(); return
1516
1529
  }
1517
- if (f.type === 'question/resolved') { state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId); renderPending(); return }
1518
1530
  if (f.type === 'session/queue') { state.queues[f.sessionId] = f.items || []; renderQueue(); return }
1519
1531
  if (f.type === 'session/jobs') { state.jobs[f.sessionId] = f.jobs || []; renderJobs(); return }
1520
1532
  if (f.type === 'session/projection') { applyProjection(f.sessionId, f.key, f.value, f.seq); return }
@@ -1578,6 +1590,7 @@ function setCompactionStatus(sessionId, next) {
1578
1590
  }
1579
1591
  if (previous?.active && previous.notify && next?.notify !== false && ['complete', 'failed'].includes(next?.phase)) {
1580
1592
  const command = previous.command || 'compact'
1593
+ if (command === 'export' && next?.phase === 'complete' && state.current === sessionId && typeof downloadSessionExport === 'function') void downloadSessionExport(sessionId)
1581
1594
  if (next?.phase === 'failed') toast(command === 'compact'
1582
1595
  ? t('session.compactFailed', { msg: next.message || t('send.failed') })
1583
1596
  : t('session.commandFailed', { command, msg: next.message || t('send.failed') }), 'err')
@@ -2033,34 +2046,41 @@ function renderWorkspaceNavigation() {
2033
2046
  if ($('modal-new-session') && !$('modal-new-session').classList.contains('hidden')) renderNewSessionWorkspace()
2034
2047
  return items
2035
2048
  }
2036
- async function refreshWorkbench() {
2049
+ async function refreshWorkbench({ discover = false } = {}) {
2037
2050
  const connection = captureConnection(), request = ++workbenchRequest
2038
2051
  const valid = () => connection.valid() && request === workbenchRequest
2052
+ const sharedRead = (name, read) => window.DshNetwork?.shareRead ? window.DshNetwork.shareRead(JSON.stringify([connection.server, connection.token, name]), read) : read()
2039
2053
  if (!state.token) return
2054
+ const workspaceRead = sharedRead('workspace.list', () => connection.valid() ? rpc('workspace.list', {}) : null).catch(() => null)
2040
2055
  try {
2041
- const res = await fetch(apiUrl('/workbench'), {
2042
- headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }
2056
+ const target = apiUrl('/workbench')
2057
+ const res = await sharedRead('workbench', async () => {
2058
+ if(!connection.valid())return {ok:false,value:null}
2059
+ const response = await fetch(target, {
2060
+ headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() }, signal: AbortSignal.timeout(10000)
2061
+ })
2062
+ return { ok: response.ok, value: await response.json().catch(() => null) }
2043
2063
  })
2044
2064
  if (!valid()) return
2045
2065
  if (res.ok) {
2046
- const value = await res.json().catch(() => null)
2066
+ const value = res.value
2047
2067
  if (!valid()) return
2048
2068
  if (value && typeof value.bound === 'boolean') state.wb = value
2049
2069
  }
2050
2070
  } catch {}
2051
2071
  if (!valid()) return
2052
2072
  try {
2053
- const value = await rpc('workspace.list', {})
2073
+ const value = await workspaceRead
2054
2074
  if (!valid()) return
2055
- state.wbProjects = Array.isArray(value?.items) ? value.items : []
2056
- state.wbArchived = Array.isArray(value?.archivedSessionIds) ? value.archivedSessionIds : []
2075
+ if (value) state.wbProjects = Array.isArray(value.items) ? value.items : []
2076
+ if (value) state.wbArchived = Array.isArray(value.archivedSessionIds) ? value.archivedSessionIds : []
2057
2077
  } catch {
2058
2078
  if (!valid()) return
2059
2079
  state.wbProjects = []
2060
2080
  state.wbArchived = []
2061
2081
  }
2062
2082
  // 以磁盘实际目录为准同步工作台项目:删除目录后不再残留,新增子目录自动收纳。
2063
- if (state.wb?.bound && state.wb.path) {
2083
+ if (discover && state.wb?.bound && state.wb.path) {
2064
2084
  try {
2065
2085
  const listRes = await fetch(fsApiUrl('/list', { path: state.wb.path }), { headers: fsHeaders() })
2066
2086
  if (!valid()) return
@@ -2124,7 +2144,7 @@ function renderWorkbench() {
2124
2144
  const open = !!state.wbOpenProjects[id]
2125
2145
  const sessions = orderedWorkspaceSessions(id, (w.sessionIds || []).map(sid => state.byId.get(sid)).filter(isVisibleSession).filter(s => !archivedSet.has(s.sessionId)))
2126
2146
  const body = open ? `<div class="wb-sessions">${sessions.length ? sessions.map(s => `
2127
- <div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}">
2147
+ <div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}" role="button" tabindex="0" aria-label="${esc(sessionLabelOf(s))}">
2128
2148
  <button class="wb-session" type="button" data-wb-session="${esc(s.sessionId)}" data-motion-key="${esc(s.sessionId)}">
2129
2149
  <span class="wb-session-drag-handle" data-reorder-handle aria-hidden="true">⠿</span>
2130
2150
  <span class="wb-session-title">${esc(sessionLabelOf(s))}</span>
@@ -2229,7 +2249,7 @@ function renderSessions() {
2229
2249
  const badge = goal ? `<span class="sc-badge ${goal.phase === 'active' ? 'goal-active' : ''}">${esc(t('sessions.goalBadge', { phase: goal.phase || '?' }))}</span>` : ''
2230
2250
  const queueBadge = queueN ? `<span class="sc-badge">${esc(t('sessions.queueBadge', { n: queueN }))}</span>` : ''
2231
2251
  const archiveButton = archivedSet.has(s.sessionId) ? '' : `<button type="button" class="sc-archive-btn" data-archive-session="${esc(s.sessionId)}">${esc(t('session.archive'))}</button>`
2232
- return `<div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}">
2252
+ return `<div class="session-swipe" data-session-swipe data-id="${esc(s.sessionId)}" role="button" tabindex="0" aria-label="${esc(sessionLabelOf(s))}">
2233
2253
  <div class="session-card ${state.current === s.sessionId ? 'current' : ''}">
2234
2254
  <div class="sc-title">${esc(title)}</div>
2235
2255
  <div class="sc-meta">
@@ -3060,7 +3080,7 @@ async function runSlashCommand(text) {
3060
3080
  const res = await fetch(apiUrl('/remote/api/command'), {
3061
3081
  method: 'POST',
3062
3082
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': CAP?.isNativePlatform?.() ? 'app' : 'web', ...clientIdHeaders() },
3063
- body: JSON.stringify({ sessionId, line: clean }),
3083
+ body: JSON.stringify({ sessionId, line: clean, async: true }),
3064
3084
  ...(signal ? { signal } : {})
3065
3085
  })
3066
3086
  if (!connection.valid()) return true
@@ -3074,7 +3094,7 @@ async function runSlashCommand(text) {
3074
3094
  if (data?.ok === false) { toast(data.message || t('send.failed'), 'err'); return true }
3075
3095
  if (data?.ok && data.executed === true) {
3076
3096
  if (data.accepted) {
3077
- if (command === 'compact') {
3097
+ if (command === 'compact' || command === 'export') {
3078
3098
  setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
3079
3099
  } else {
3080
3100
  state.pendingCommands[sessionId] = command
@@ -3202,11 +3222,13 @@ function composerIsBusy() {
3202
3222
  return !!state.byId.get(state.current)?.running || (state.queues[state.current] || []).some(item => item.placement === 'queued')
3203
3223
  }
3204
3224
  function composerSendMode(alternate = false) {
3225
+ if (window.DshWorkflow?.isMounted()) return alternate && composerIsBusy() ? 'steer' : 'queue'
3205
3226
  if (!steerSendingEnabled() || !composerIsBusy()) return 'queue'
3206
3227
  const preferred = LS.get('busySendMode', 'queue') === 'steer' ? 'steer' : 'queue'
3207
3228
  return alternate ? (preferred === 'queue' ? 'steer' : 'queue') : preferred
3208
3229
  }
3209
3230
  function renderComposerSend() {
3231
+ window.DshWorkflow?.update()
3210
3232
  const enabled = steerSendingEnabled() && composerIsBusy()
3211
3233
  const mode = composerSendMode()
3212
3234
  for (const id of ['btn-send', 'btn-fs-send']) {
@@ -3225,6 +3247,7 @@ function renderComposerSend() {
3225
3247
  node.classList.toggle('hidden', !node.textContent)
3226
3248
  node.dataset.phase = feedback?.phase || 'hint'
3227
3249
  }
3250
+ window.DshWorkflow?.update()
3228
3251
  }
3229
3252
  function setComposerSendFeedback(context, key, phase, message = '') {
3230
3253
  composerSendFeedback.set(context, { key, phase, message })
@@ -3301,7 +3324,7 @@ async function sendSessionContent(text, images, requestedMode = 'queue') {
3301
3324
  if ((!clean && !images.length) || !state.current || composerSending) return false
3302
3325
  const sessionId = state.current
3303
3326
  const context = composerContext()
3304
- const mode = requestedMode === 'steer' && steerSendingEnabled() && composerIsBusy() ? 'steer' : 'queue'
3327
+ const mode = requestedMode === 'steer' && (window.DshWorkflow?.isMounted() || steerSendingEnabled()) && composerIsBusy() ? 'steer' : 'queue'
3305
3328
  if (mode === 'steer' && clean.startsWith('/')) {
3306
3329
  setComposerSendFeedback(context, 'send.steerSlash', 'error')
3307
3330
  return false
@@ -3575,6 +3598,7 @@ async function newSession() {
3575
3598
  if (!workspaceItems().length) await refreshWorkbench()
3576
3599
  const preferred = workspaceById(state.workspaceFilter)?.workspaceId || LS.get('lastNewSessionWorkspaceV1', '')
3577
3600
  renderNewSessionWorkspace(preferred)
3601
+ if (workspaceById(state.workspaceFilter) || workspaceItems().length === 1) return createSessionInWorkspace()
3578
3602
  $('modal-new-session').classList.remove('hidden')
3579
3603
  }
3580
3604
  function renderNewSessionWorkspace(preferredId = '') {
@@ -3612,9 +3636,12 @@ async function createSessionInWorkspace() {
3612
3636
  LS.set('lastNewSessionWorkspaceV1', workspaceId)
3613
3637
  closeNewSessionModal()
3614
3638
  toast(t('home.created'), 'ok')
3615
- await refreshSessions()
3616
- if (!connection.valid()) return
3617
- openSession(v.sessionId)
3639
+ const workspace = workspaceById(workspaceId)
3640
+ const session = { sessionId: v.sessionId, cwd: workspace?.path || '', running: false, projections: { values: {} } }
3641
+ state.byId.set(session.sessionId, session)
3642
+ state.sessions.unshift(session)
3643
+ void openSession(session.sessionId)
3644
+ void refreshSessions()
3618
3645
  } finally { createSessionInWorkspace.busy = false; button.disabled = false }
3619
3646
  }
3620
3647
 
@@ -3752,6 +3779,7 @@ window.addEventListener('offline',()=>startOverviewDetection(true))
3752
3779
  document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}})
3753
3780
 
3754
3781
  function renderOverview() {
3782
+ window.DshWorkflow?.update()
3755
3783
  const ring = $('overview-pulse-ring')
3756
3784
  if (!ring) return
3757
3785
  const checks = overviewChecks()
@@ -3788,7 +3816,7 @@ function renderOverview() {
3788
3816
  ...state.questions.map(q => ({ kind: 'question', item: q }))
3789
3817
  ]
3790
3818
  $('overview-attention-count').textContent = pending.length ? t('overview.pendingCount', { n: pending.length }) : '—'
3791
- $('overview-attention-list').innerHTML = pending.length ? pending.slice(0, 3).map(({ kind, item }) => {
3819
+ $('overview-attention-list').innerHTML = pending.length ? pending.map(({ kind, item }) => {
3792
3820
  const title = sessionLabelOf(state.byId.get(item.sessionId))
3793
3821
  if (kind === 'approval') return `<div class="overview-attention-item" data-overview-approval="${esc(item.approvalId)}">
3794
3822
  <span class="overview-item-mark">⌁</span><span class="overview-item-copy"><span class="overview-item-title">${esc(item.toolName || t('tool.default'))}</span><span class="overview-item-desc">${esc(approvalDetail(item))} · ${esc(title)}</span></span>
@@ -3905,16 +3933,16 @@ function renderSessionPending() {
3905
3933
  <div class="pc-desc">${esc(approvalDetail(item))}</div>
3906
3934
  <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>
3907
3935
  </article>`
3908
- return `<article class="pending-card question" data-session-question="${esc(item.rpcId)}">
3909
- <div class="pc-title">❓ ${esc((item.questions || []).map(question => question.question).filter(Boolean).join(' / ') || t('notify.questionTitle'))}</div>
3910
- <div class="goal-actions"><button type="button" class="mini-btn" data-session-answer>${t('pending.answer')}</button></div>
3911
- </article>`
3936
+ return `<button type="button" class="pending-card question" data-session-question="${esc(item.rpcId)}" aria-haspopup="dialog">
3937
+ <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>
3938
+ <span class="question-summary">${esc(questionSummary(item))}</span>
3939
+ </button>`
3912
3940
  }).join('')}</div>`
3913
3941
  box.querySelectorAll('[data-session-approve]').forEach(button => {
3914
3942
  button.addEventListener('click', () => approveApproval(button.closest('[data-session-approval]')?.dataset.sessionApproval || '', button.dataset.sessionApprove === '1'))
3915
3943
  })
3916
- box.querySelectorAll('[data-session-answer]').forEach(button => {
3917
- button.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === button.closest('[data-session-question]')?.dataset.sessionQuestion)))
3944
+ box.querySelectorAll('[data-session-question]').forEach(button => {
3945
+ button.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === button.dataset.sessionQuestion)))
3918
3946
  })
3919
3947
  }
3920
3948
 
@@ -3933,21 +3961,42 @@ async function approveApproval(id, allow) {
3933
3961
  }
3934
3962
  if (!connection.valid()) return
3935
3963
  toast(ok ? (allow ? t('pending.allowed') : t('pending.rejected')) : t('pending.stale'), ok ? 'ok' : 'err')
3964
+ if (ok) clearPendingNotification({ type: 'approval/resolved', approvalId: a.approvalId })
3936
3965
  state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
3937
3966
  renderPending()
3938
3967
  }
3939
3968
 
3969
+ function questionSummary(q) {
3970
+ return (q.questions || []).map(item => String(item.question || '').replace(/\[([^\]]+)\]\([^)]+\)/g, '$1').replace(/[*_`#>]/g, '')).join(' / ').replace(/\s+/g, ' ').trim().slice(0, 240)
3971
+ }
3972
+
3973
+ function questionMarkup(item) {
3974
+ const text = String(item.question || '')
3975
+ return (item.header ? `<strong>${esc(item.header)}</strong>` : '') + (window.mdToHtml ? window.mdToHtml(text, { richContent: false, fileLinks: true }) : esc(text))
3976
+ }
3977
+
3978
+ function fitQuestionViewport() {
3979
+ const viewport = window.visualViewport
3980
+ const modal = $('modal-question')
3981
+ if (!modal || !viewport) return
3982
+ modal.style.top = viewport.offsetTop + 'px'
3983
+ modal.style.height = viewport.height + 'px'
3984
+ modal.style.bottom = 'auto'
3985
+ }
3986
+
3940
3987
  function openQuestionModal(q) {
3941
3988
  if (!q) return
3942
3989
  state.questionModal = q
3943
3990
  $('question-body').innerHTML = q.questions.map((item, i) => `
3944
3991
  <div class="q-item">
3945
- <div class="q-text">${esc(item.header ? item.header + ':' : '')}${esc(item.question)}</div>
3992
+ <div class="q-text md">${questionMarkup(item)}</div>
3946
3993
  ${(item.options || []).map((o, j) => `
3947
3994
  <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('')}
3948
3995
  <textarea rows="2" placeholder="${t('question.customPlaceholder')}" data-qcustom="${i}"></textarea>
3949
3996
  </div>`).join('')
3950
3997
  $('modal-question').classList.remove('hidden')
3998
+ $('question-body').scrollTop = 0
3999
+ fitQuestionViewport()
3951
4000
  }
3952
4001
 
3953
4002
  async function submitQuestion() {
@@ -3974,6 +4023,7 @@ async function submitQuestion() {
3974
4023
  }
3975
4024
  if (!connection.valid()) return
3976
4025
  if (ok) {
4026
+ clearPendingNotification({ type: 'question/resolved', questionRpcId: q.rpcId })
3977
4027
  toast(t('question.submitted'), 'ok')
3978
4028
  if (state.questionModal === q) { $('modal-question').classList.add('hidden'); state.questionModal = null }
3979
4029
  state.questions = state.questions.filter(x => x.rpcId !== q.rpcId)
@@ -4505,6 +4555,8 @@ async function runFsUpload(up) {
4505
4555
  const xhr = new XMLHttpRequest()
4506
4556
  up.xhr = xhr
4507
4557
  xhr.open('POST', fsApiUrl('/upload', params))
4558
+ xhr.timeout = window.DshNetwork?.profile().weak ? 180000 : 90000
4559
+ xhr.ontimeout = () => { if (up.xhr === xhr) up.xhr = null; reject(new Error('上传等待超时,可查询进度后继续')) }
4508
4560
  xhr.setRequestHeader('authorization', 'Bearer ' + state.token)
4509
4561
  xhr.setRequestHeader('x-dsh-remote-client', CAP?.isNativePlatform?.() ? 'app' : 'web')
4510
4562
  if (CLIENT_ID) xhr.setRequestHeader('x-dsh-remote-client-id', CLIENT_ID)
@@ -4557,7 +4609,8 @@ async function runFsUpload(up) {
4557
4609
 
4558
4610
  while (up.offset < up.size) {
4559
4611
  if (up.cancelled) return
4560
- const end = Math.min(up.offset + FS_CHUNK_SIZE, up.size)
4612
+ const chunkSize = up.chunkSize || (window.DshNetwork?.profile().weak ? 256 * 1024 : FS_CHUNK_SIZE)
4613
+ const end = Math.min(up.offset + chunkSize, up.size)
4561
4614
  const blob = up.file.slice(up.offset, end)
4562
4615
  const before = hasher.clone()
4563
4616
  const chunkBytes = new Uint8Array(await blob.arrayBuffer())
@@ -4569,7 +4622,10 @@ async function runFsUpload(up) {
4569
4622
  const params = { path: up.path, name: up.name, session: up.session, offset: String(up.offset), size: String(up.size) }
4570
4623
  if (isLast) { params.finish = '1'; params.sha256 = hasher.hex() }
4571
4624
  if (overwrite) params.overwrite = '1'
4625
+ const startedAt = Date.now()
4572
4626
  const r = await uploadChunk(params, blob)
4627
+ const elapsed = Date.now() - startedAt
4628
+ up.chunkSize = elapsed > 15000 ? Math.max(65536, Math.floor(chunkSize / 2)) : elapsed < 2000 ? Math.min(FS_CHUNK_SIZE, chunkSize * 2) : chunkSize
4573
4629
  if (r.status === 401) { fsAuthError(401); return }
4574
4630
  if (r.status === 200 && r.json.offset != null) { up.offset = r.json.offset; continue }
4575
4631
  if (r.status === 201) {
@@ -4661,8 +4717,8 @@ async function runFsUpload(up) {
4661
4717
  toast(e.message, 'err')
4662
4718
  return
4663
4719
  }
4664
- hideFsProgress()
4665
- setFsButtons(false)
4720
+ up.paused = true
4721
+ setFsButtons(true, true)
4666
4722
  toast(t('fs.uploadInterrupted', { msg: e.message }), 'err')
4667
4723
  }
4668
4724
  }
@@ -5159,6 +5215,7 @@ async function fetchAnnouncements() {
5159
5215
  state.announcements = normalized.sort((a, b) => Number(b.publishedAt || 0) - Number(a.publishedAt || 0))
5160
5216
  storeAnnouncementHistory(normalized)
5161
5217
  renderAnnouncementBoard()
5218
+ if (window.DshWorkflow?.isMounted()) return false
5162
5219
  const seen = readSeenAnnouncements()
5163
5220
  const items = normalized.filter(item => !seen[item.id])
5164
5221
  .sort((a, b) => b.publishedAt - a.publishedAt)
@@ -5292,7 +5349,7 @@ async function checkUpdate(silent) {
5292
5349
  const res = await fetch(base + '/update.json?t=' + Date.now() + '&local=' + encodeURIComponent(state.localVersion))
5293
5350
  if (!res.ok) throw new Error('HTTP ' + res.status)
5294
5351
  const info = await res.json()
5295
- openNotesModal(info)
5352
+ if (!silent || !window.DshWorkflow?.isMounted()) openNotesModal(info)
5296
5353
  if (info.version && cmpVersion(info.version, state.localVersion) > 0) {
5297
5354
  state.updateInfo = info
5298
5355
  const hasNotes = !!(info.notes && String(info.notes).trim())
@@ -5442,6 +5499,56 @@ async function downloadUpdate() {
5442
5499
 
5443
5500
  /* ---------------- 通知 ---------------- */
5444
5501
  const CAP = window.Capacitor || null
5502
+ const pendingNotificationSeen = new Set()
5503
+ function notifyPendingRequest(full, title, body) {
5504
+ const bridge = window.NativeBackground
5505
+ if (bridge?.handlePendingEvent) {
5506
+ bridge.handlePendingEvent(bgBase(), state.token || '', JSON.stringify(full), LS.get('notify', '0') === '1')
5507
+ return
5508
+ }
5509
+ const key = connectionGeneration + ':' + (full.payload?.approvalId || full.rpcId)
5510
+ if (LS.get('notify', '0') !== '1' || pendingNotificationSeen.has(key)) return
5511
+ if (pendingNotificationSeen.size >= 512) pendingNotificationSeen.delete(pendingNotificationSeen.values().next().value)
5512
+ pendingNotificationSeen.add(key)
5513
+ notify(title, body)
5514
+ }
5515
+ function clearPendingNotification(payload) {
5516
+ window.NativeBackground?.handlePendingEvent?.(bgBase(), state.token || '', JSON.stringify({ payload }), false)
5517
+ }
5518
+
5519
+ let pendingNavigationBusy = false, pendingNavigationReady = false
5520
+ async function openPendingNavigation() {
5521
+ const bridge = window.NativeBackground
5522
+ if (!pendingNavigationReady || pendingNavigationBusy || !bridge?.getPendingNavigation) return
5523
+ const raw = bridge.getPendingNavigation()
5524
+ if (!raw) return
5525
+ pendingNavigationBusy = true
5526
+ try {
5527
+ const target = JSON.parse(raw)
5528
+ const matches = (base, token) => bridge.matchesPendingNavigation(base, token, target.identity)
5529
+ if (!matches(bgBase(), state.token || '')) {
5530
+ const server = state.servers.find(s => matches(s.url, serverToken(s)))
5531
+ if (!server) { toast(t('notify.hostUnavailable'), 'err'); bridge.acknowledgePendingNavigation(raw); return }
5532
+ state.activeGroup = server.group
5533
+ state.groupActive[server.group] = server.id
5534
+ state.server = server.url; state.token = serverToken(server)
5535
+ LS.set('token', state.token)
5536
+ saveServers(); syncBgConfig(); renderServers(); openStreams()
5537
+ }
5538
+ bridge.acknowledgePendingNavigation(raw)
5539
+ const connection = captureConnection()
5540
+ await refreshSessions()
5541
+ if (!connection.valid()) return
5542
+ if (state.byId.has(target.sessionId)) await openSession(target.sessionId)
5543
+ else { showView('view-activity'); toast(t('question.stale'), 'err') }
5544
+ } catch (error) { toast(error.message, 'err') }
5545
+ finally {
5546
+ pendingNavigationBusy = false
5547
+ const next = bridge.getPendingNavigation()
5548
+ if (next && next !== raw) void openPendingNavigation()
5549
+ }
5550
+ }
5551
+ window.addEventListener('dsh-pending-navigation', () => void openPendingNavigation())
5445
5552
  async function ensureNotify() {
5446
5553
  // App 内走原生通知插件(WebView 的 Web Notification 在 MIUI 拿不到权限)
5447
5554
  if (CAP?.isNativePlatform?.()) {
@@ -6210,6 +6317,8 @@ async function openModelConfigDocument() {
6210
6317
  }
6211
6318
  /* ---------------- 视图切换 ---------------- */
6212
6319
  function showView(id) {
6320
+ window.DshWorkflow?.close()
6321
+ if (window.DshWorkflow?.isMounted() && id === 'view-activity') id = 'view-home'
6213
6322
  if (id !== 'view-session') conversationView?.pause()
6214
6323
  if (id !== 'view-session' && document.body.classList.contains('in-session') && state.current) void archiveEmptySessionOnLeave(state.current)
6215
6324
  for (const v of ['view-home', 'view-files', 'view-session', 'view-activity', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
@@ -7034,7 +7143,11 @@ function bindUi() {
7034
7143
  if (first.matches('button')) first.focus({ preventScroll: true })
7035
7144
  }
7036
7145
  })
7037
- // 会话列表点击
7146
+ // 会话列表点击与键盘激活共享目标。
7147
+ $('session-list').addEventListener('keydown', event => {
7148
+ const card = event.target.closest('[data-session-swipe]')
7149
+ if (card && event.target === card && ['Enter', ' '].includes(event.key)) { event.preventDefault(); void openSession(card.dataset.id) }
7150
+ })
7038
7151
  $('session-list').addEventListener('click', (e) => {
7039
7152
  if (swipeSuppressClickUntil > Date.now()) { swipeSuppressClickUntil = 0; return }
7040
7153
  if (e.target.closest('[data-archived-toggle]')) {
@@ -7267,6 +7380,8 @@ function bindUi() {
7267
7380
  // 提问
7268
7381
  $('question-submit').addEventListener('click', submitQuestion)
7269
7382
  $('question-later').addEventListener('click', () => $('modal-question').classList.add('hidden'))
7383
+ window.visualViewport?.addEventListener('resize', fitQuestionViewport)
7384
+ window.visualViewport?.addEventListener('scroll', fitQuestionViewport)
7270
7385
  // goal
7271
7386
  $('goal-close').addEventListener('click', () => $('modal-goal').classList.add('hidden'))
7272
7387
  $('goal-edit').addEventListener('click', submitGoalEdit)
@@ -7387,12 +7502,14 @@ function bindUi() {
7387
7502
  toast(t(action === 'send' ? 'settings.mobileEnterSend' : 'settings.mobileEnterNewline'), 'ok')
7388
7503
  })
7389
7504
  $('opt-notify').checked = LS.get('notify', '0') === '1'
7505
+ window.NativeBackground?.setPendingNotificationsEnabled?.($('opt-notify').checked)
7390
7506
  $('opt-notify').addEventListener('change', async (e) => {
7391
7507
  if (e.target.checked) {
7392
7508
  const ok = await ensureNotify()
7393
7509
  if (!ok) { e.target.checked = false; return toast(t('settings.notifyDenied')) }
7394
7510
  }
7395
7511
  LS.set('notify', e.target.checked ? '1' : '0')
7512
+ window.NativeBackground?.setPendingNotificationsEnabled?.(e.target.checked)
7396
7513
  })
7397
7514
  $('opt-peak-remind').checked = peakRemindOn()
7398
7515
  $('opt-peak-remind').addEventListener('change', async (e) => {
@@ -7475,7 +7592,11 @@ function bindUi() {
7475
7592
 
7476
7593
  bindRail()
7477
7594
 
7478
- window.DshChatFiles?.bind($('history'), () => { const c=captureConnection(); return { ...c,sessionId:state.current,cwd:sessionCwd(state.byId.get(state.current)),native:!!CAP?.isNativePlatform?.(),headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast } })
7595
+ for (const id of ['history', 'question-body']) window.DshChatFiles?.bind($(id), () => {
7596
+ const c=captureConnection(),sessionId=id==='history'?state.current:state.questionModal?.sessionId
7597
+ return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:!!CAP?.isNativePlatform?.(),headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,preview:(path,name)=>window.DshWorkflow?.preview({...c,headers:{authorization:'Bearer '+c.token}},path,name),
7598
+ valid:()=>c.valid()&&sessionId===(id==='history'?state.current:state.questionModal?.sessionId) }
7599
+ })
7479
7600
  initCustomSelects()
7480
7601
 
7481
7602
  $('btn-history-latest').addEventListener('click',()=>{getConversationView().latest();if(state.history.tailEvicted)void loadHistory(true)})
@@ -7525,9 +7646,88 @@ async function boot() {
7525
7646
  startAnnouncementPolling()
7526
7647
  scheduleStartupNotices()
7527
7648
  renderPending()
7649
+ pendingNavigationReady = true
7650
+ void openPendingNavigation()
7528
7651
  }
7529
7652
 
7530
7653
  document.addEventListener('DOMContentLoaded', boot)
7654
+ document.addEventListener('DOMContentLoaded', mountWorkflow)
7655
+
7656
+ function mountWorkflow() {
7657
+ window.DshWorkflow?.mount({
7658
+ desktop: false,
7659
+ start: () => { if (!$('view-activity').classList.contains('hidden')) showView('view-home') },
7660
+ snapshot: () => ({ token: !!state.token, host: currentServerEntry()?.note || state.server || location.host,
7661
+ gateway: activeGatewayHealth()?.ok || !!state.streamsOk?.mux, dsh: dshReachable(),
7662
+ mux: !!state.streamsOk?.mux, hostEvents: !!state.streamsOk?.host,
7663
+ pending: state.approvals.length + state.questions.length, busy: composerIsBusy(), sending: composerSending }),
7664
+ settings: name => { showView('view-settings'); showSettingsPage(name) },
7665
+ plugins: () => showView('view-plugins'), models: loadSessionModels, send: sendMessage,
7666
+ feedback: openFeedbackModal,
7667
+ browse: () => { closeNewSessionModal(); showView('view-files') },
7668
+ register: async () => {
7669
+ const connection=captureConnection(), path=state.fs.path
7670
+ if(!path)return toast('请先选择主机目录','err')
7671
+ try {
7672
+ const value=await rpc('workspace.create',{path})
7673
+ if(!connection.valid()||!value?.workspace)return
7674
+ state.wbProjects=[...state.wbProjects.filter(w=>w.workspaceId!==value.workspace.workspaceId),value.workspace]
7675
+ state.workspaceFilter=value.workspace.workspaceId;closeWorkspaceModal();await newSession()
7676
+ }catch(error){if(connection.valid())toast(error.message,'err')}
7677
+ },
7678
+ command: runSlashCommand, refresh: refreshAll, retry: () => { startOverviewDetection(true); void refreshAll() },
7679
+ operations: () => { const connection=captureConnection(); return { url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid } },
7680
+ discover: () => { if (confirm('登记当前绑定目录下的子目录为工作区?')) void refreshWorkbench({ discover: true }) },
7681
+ files: () => {
7682
+ const workspace = workspaceForSession(state.byId.get(state.current))
7683
+ if (workspace) return openWorkspaceFiles(workspace.workspaceId)
7684
+ const cwd = sessionCwd(state.byId.get(state.current))
7685
+ if (!cwd) return toast('当前会话没有工作目录', 'err')
7686
+ state.fs.loaded = true; showView('view-files'); void loadFs(cwd, { resetRoot: true })
7687
+ },
7688
+ clear: clearWorkflowData,
7689
+ admin: () => {
7690
+ const url = new URL(apiUrl('/admin/'), location.href)
7691
+ // Open authenticated management through its own login flow. No credential
7692
+ // in a newly created URL, browser history, or referrer.
7693
+ window.open(url.href, '_blank', 'noopener,noreferrer')
7694
+ },
7695
+ recover: (row, receipt) => {
7696
+ const value = receipt.result?.result?.value
7697
+ if (row.method === 'session.create' && value?.sessionId) void openSession(value.sessionId)
7698
+ if (row.sessionId === state.current) void resyncCurrentSession()
7699
+ },
7700
+ })
7701
+ }
7702
+
7703
+ async function clearWorkflowData(kind) {
7704
+ const english = window.I18N?.lang === 'en'
7705
+ const messages = { history: english ? 'Clear cached conversation history on this device?' : '清除这台设备的会话历史缓存?主机记录保留。',
7706
+ connection: english ? 'Remove the current address and its saved credential? Other addresses remain.' : '移除当前地址和保存的凭证?其他连接条目保留。',
7707
+ all: english ? 'Clear all Remote settings and credentials on this device and stop background reminders?' : '清除本机全部 Remote 配置与凭证,并停止后台轮询和提醒?主机数据保留。' }
7708
+ if (!confirm(messages[kind])) return
7709
+ if (kind === 'history') {
7710
+ clearTimeout(scheduleHistoryCacheSave._t)
7711
+ await window.DshHistory.cacheClear()
7712
+ for (let i=localStorage.length-1;i>=0;i--) { const key=localStorage.key(i); if (/^dsh-remote-(?:sessions|history)/.test(key)) localStorage.removeItem(key) }
7713
+ return toast(english ? 'History cache cleared' : '历史缓存已清除', 'ok')
7714
+ }
7715
+ window.NativeBackground?.saveBackgroundConfig?.(JSON.stringify({ enabled:false, base:'', token:'', clientId:'', intervalMin:1, notifyTaskDone:false }))
7716
+ window.NativeBackground?.setPendingNotificationsEnabled?.(false)
7717
+ if (kind === 'connection') {
7718
+ const current = currentServerEntry()
7719
+ if (current) state.servers = state.servers.filter(server => server.id !== current.id)
7720
+ state.groupActive[state.activeGroup] = ''
7721
+ state.token = ''; state.server = ''; LS.del('token'); LS.del('server'); saveServers()
7722
+ closeStream('mux'); closeStream('host'); stopPolling(); renderServers(); showView('view-settings'); showSettingsPage('servers')
7723
+ return
7724
+ }
7725
+ await cancelPeakReminders()
7726
+ clearTimeout(scheduleHistoryCacheSave._t)
7727
+ await window.DshHistory.cacheClear()
7728
+ window.DshWorkflow.clearStorage()
7729
+ location.reload()
7730
+ }
7531
7731
 
7532
7732
  function openPluginPage(route = 'manage') {
7533
7733
  const connection = captureConnection()