dsh-remote-plugin 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -132,6 +132,8 @@ for (const key of ['server', 'token']) {
132
132
  window.DshInsights?.close()
133
133
  window.DshExtensions?.close()
134
134
  window.DshExtensions?.invalidateCapabilities()
135
+ window.DshFileInbox?.reset()
136
+ window.DshSessionDeck?.reset()
135
137
  if (typeof document !== 'undefined') document.getElementById('btn-insights')?.classList.add('hidden')
136
138
  if(typeof document!=='undefined') {
137
139
  const identityGeneration=connectionGeneration
@@ -2412,7 +2414,7 @@ function blockHtml(b,index=0,context={}) {
2412
2414
  if (b.type==='thinking'||b.type==='reasoning') return window.DshActivity.reasoning({text:b.text??b.content??'',key:window.DshActivity.reasoningKey(context,index,key)})
2413
2415
  if (b.type==='tool-call'||b.type==='tool-result') return window.DshActivity.tool({key,name:b.name||b.toolName,...(b.type==='tool-call'?{args:b.arguments??b.args??b.input}:{result:b.result??b.output??b.content??b,error:!!(b.error||b.ok===false||b.isError)})})
2414
2416
  }
2415
- if (b.type === 'text') return `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true, imageLabel: t('block.image') }) : esc(b.text ?? '')}</div>`
2417
+ if (b.type === 'text') return window.DshActivity.hasVisibleText(b.text) ? `<div class="md">${window.mdToHtml ? window.mdToHtml(b.text ?? '', { fileLinks: true, imageLabel: t('block.image') }) : esc(b.text ?? '')}</div>` : ''
2416
2418
  if (b.type === 'file' && typeof window !== 'undefined' && window.DshChatFiles) return window.DshChatFiles.render(b)
2417
2419
  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>`
2418
2420
  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>`
@@ -2585,27 +2587,25 @@ async function renderSessionCards() {
2585
2587
  let html = ''
2586
2588
  if (goal && !isGoalTerminal(goal)) {
2587
2589
  const collapsed = isGoalCollapsed(sessionId, goal)
2588
- html += `<div class="ds-goal-disclosure${collapsed ? ' is-collapsed' : ''}">
2590
+ html += `<div data-deck-kind="goal" class="ds-goal-disclosure${collapsed ? ' is-collapsed' : ''}">
2589
2591
  <div id="goal-panel-desktop" class="ds-card ds-goal-card${collapsed ? ' hidden' : ''}">
2590
- <div class="ds-goal-card-head"><div class="ds-card-title">${t('goal.title')}</div>
2592
+ <div class="ds-goal-card-head"><div class="ds-card-title">${esc(window.DshSessionDeck?.goalState(goal.phase) || goal.phase || t('goal.title'))}</div>
2591
2593
  <button type="button" class="ds-goal-collapse-btn" data-goal-collapse="1" aria-expanded="true" aria-controls="goal-panel-desktop" title="${esc(t('goal.collapse'))}"><span aria-hidden="true">›</span>${t('goal.collapseShort')}</button>
2592
2594
  </div>
2593
2595
  <div class="ds-goal-obj">${esc(goal.objective || '')}</div>
2594
- <div class="ds-goal-phase">phase: ${esc(goal.phase || '?')} · revision ${goal.revision ?? '?'}</div>
2595
2596
  <div class="ds-goal-actions">
2596
2597
  ${goal.phase === 'active' ? `<button class="ds-mini-btn" data-goal="pause">${t('goal.pause')}</button>` : `<button class="ds-mini-btn" data-goal="resume">${t('goal.resume')}</button>`}
2597
2598
  <button class="ds-mini-btn" data-goal="complete">${t('goal.complete')}</button>
2598
- <button class="ds-mini-btn" data-goal="edit">${t('goal.edit')}</button>
2599
- <button class="ds-mini-btn" data-goal="clear">${t('goal.clear')}</button>
2599
+ <details class="deck-more" data-deck-details="goal-${esc(goal.id || '')}"><summary>${I18N.lang === 'en' ? 'More' : '更多'}</summary><div class="deck-full-content">${esc(goal.objective || '')}<p>revision ${esc(goal.revision ?? '?')}</p></div><div class="ds-goal-actions"><button class="ds-mini-btn" data-goal="edit">${t('goal.edit')}</button><button class="ds-mini-btn" data-goal="clear">${t('goal.clear')}</button></div></details>
2600
2600
  </div>
2601
2601
  </div>
2602
2602
  <button type="button" class="ds-goal-side-tab${collapsed ? '' : ' hidden'}" data-goal-collapse="0" aria-expanded="false" aria-controls="goal-panel-desktop" aria-label="${esc(t('goal.expand'))}" title="${esc(t('goal.expand'))}"><span aria-hidden="true">‹</span><span>${t('goal.title')}</span><small>${t('goal.collapsedHint')}</small></button>
2603
2603
  </div>`
2604
2604
  }
2605
2605
  if (todos?.items?.length) {
2606
- html += `<div class="ds-card"><div class="ds-card-title">${t('todos.title')}</div>${todos.items.map(item =>
2606
+ html += `<div data-deck-kind="todos" class="ds-card">${window.DshSessionDeck?.taskHtml(todos.items) || `<div class="ds-card-title">${t('todos.title')}</div>${todos.items.map(item =>
2607
2607
  `<div class="ds-todo-row"><span class="ds-pill ${item.status === 'completed' ? 'done' : item.status === 'in_progress' ? 'active' : ''}">${esc(item.status || 'pending')}</span><span>${esc(item.content || '')}</span></div>`
2608
- ).join('')}</div>`
2608
+ ).join('')}`}</div>`
2609
2609
  }
2610
2610
  box.innerHTML = html
2611
2611
  box.querySelectorAll('[data-goal]').forEach(btn =>
@@ -2942,12 +2942,13 @@ function serverLabel() {
2942
2942
  }
2943
2943
  function desktopApprovalDetail(a) {
2944
2944
  const lines = []
2945
- if (a?.reason) lines.push(String(a.reason))
2945
+ if (a?.reason) lines.push(window.DshApprovalRecords?.displayReason(a.reason) || String(a.reason))
2946
2946
  if (a?.arguments !== undefined) lines.push(safeJson(a.arguments))
2947
2947
  if (a?.callId) lines.push(`callId: ${a.callId}`)
2948
2948
  return lines.join('\n') || t('ds.approvalReason', { reason: '' })
2949
2949
  }
2950
2950
  function renderSessionPendingDesktop() {
2951
+ window.DshFileInbox?.render()
2951
2952
  const box = $('session-pending')
2952
2953
  if (!box) return
2953
2954
  const sessionId = state.current
@@ -2958,12 +2959,12 @@ function renderSessionPendingDesktop() {
2958
2959
  box.classList.toggle('hidden', !sessionId || !items.length)
2959
2960
  if (!sessionId || !items.length) { box.innerHTML = ''; return }
2960
2961
  box.innerHTML = `<div class="ds-session-pending-head"><span>${esc(t('ds.attention'))}</span><span>${items.length}</span></div><div class="ds-session-pending-list">${items.map(({ kind, item }) => {
2961
- if (kind === 'approval') return `<article class="ds-notif-card" data-session-approval="${esc(item.approvalId)}">
2962
+ if (kind === 'approval') return `<article class="ds-notif-card" data-session-approval="${esc(item.approvalId)}">${window.DshSessionDeck?.approvalHtml(item, desktopApprovalDetail(item)) || `
2962
2963
  <div class="ds-notif-head">🔐 ${t('ds.approvalTitle')}</div>
2963
2964
  <div class="ds-notif-title">${esc(item.toolName || t('ds.toolDefault'))}</div>
2964
2965
  <div class="ds-notif-body">${esc(desktopApprovalDetail(item))}</div>
2965
2966
  <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>
2966
- </article>`
2967
+ `}</article>`
2967
2968
  return `<button type="button" class="ds-notif-card question" data-session-question="${esc(item.rpcId)}" aria-haspopup="dialog">
2968
2969
  <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>
2969
2970
  <span class="ds-question-summary">${esc(questionSummary(item))}</span>
@@ -4025,7 +4026,8 @@ function openDesktopPlugins(route = 'manage') {
4025
4026
  back:()=>showView('view-settings'),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)
4026
4027
  }
4027
4028
 
4028
- function showView(id) {
4029
+ function showView(id, pluginRoute = 'manage') {
4030
+ window.DshExtensions?.closeShortcuts()
4029
4031
  if (id !== 'view-chat') window.DshSubagents?.close()
4030
4032
  document.body?.classList.toggle('viewing-subagent', id === 'view-chat' && state.byId.get(state.current)?.origin === 'subagent')
4031
4033
  window.DshWorkflow?.close()
@@ -4033,6 +4035,8 @@ function showView(id) {
4033
4035
  if (id !== 'view-chat') conversationView?.pause()
4034
4036
  if (state.view === 'view-chat' && id !== 'view-chat' && state.current) void archiveEmptySessionOnLeave(state.current)
4035
4037
  state.view = id
4038
+ window.DshFileInbox?.render()
4039
+ window.DshSessionDeck?.refresh()
4036
4040
  document.body?.classList.toggle('workflow-at-start', !!window.DshWorkflow?.isMounted() && id === 'view-sessions')
4037
4041
  for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
4038
4042
  if (id === 'view-chat') conversationView?.resume()
@@ -4046,7 +4050,7 @@ function showView(id) {
4046
4050
  else {overviewDetector?.pause();overviewPulse?.pause()}
4047
4051
  if (id === 'view-files' && !state.fs.loaded) loadFs(null, true)
4048
4052
  if (id === 'view-settings') showSettingsHome()
4049
- if (id === 'view-plugins') openDesktopPlugins()
4053
+ if (id === 'view-plugins') openDesktopPlugins(pluginRoute)
4050
4054
  else window.DshExtensions?.close()
4051
4055
  updateSessionActions()
4052
4056
  }
@@ -4146,6 +4150,11 @@ function bindSessionDialogs() {
4146
4150
  }
4147
4151
 
4148
4152
  function bindUi() {
4153
+ $('conn-badge').addEventListener('click', () => { toast(t('ds.connRefresh')); openStreams(); void refreshSessions(); startOverviewDetection(true) })
4154
+ window.DshExtensions?.bindShortcuts({ trigger: $('btn-plugin-shortcuts'), menu: $('plugin-shortcuts-menu'),
4155
+ config: () => optionalPluginConfig(), connected: () => !!state.token, hasSession: () => !!state.current,
4156
+ beforeOpen: () => setMobileSidebar(false),
4157
+ open: route => { if (route === 'context') void openInsights('context', true); else showView('view-plugins', route) } })
4149
4158
  bindSessionDialogs()
4150
4159
  getConversationView()
4151
4160
  $('btn-history-latest').addEventListener('click',()=>{getConversationView().latest();if(state.history.tailEvicted)void loadHistory(true)})
@@ -4471,3 +4480,8 @@ function mountWorkflowDesktop() {
4471
4480
 
4472
4481
  // Operation logs stay on this device; users can copy or export them.
4473
4482
  globalThis.DshDiagnostics?.configure({surface:"desktop",copy:copyText,snapshot:()=>({sessionId:state.current,server:state.server,loading:!!state.history.loading,loaded:!!state.history.loaded,count:state.history.visible.length,...globalThis.DshDiagnostics.nativeSnapshot()})})
4483
+ globalThis.DshFileInbox?.mount({ capture: captureConnection, url: apiUrl,
4484
+ context: () => ({ sessionId: state.current, inChat: state.view === 'view-chat' }),
4485
+ sessionTitle: id => state.byId.has(id) ? titleOf(state.byId.get(id)) : '', openFiles: () => showView('view-files'),
4486
+ headers: connection => ({ authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }), native: () => null })
4487
+ globalThis.DshSessionDeck?.mount({ context: () => ({ sessionId: state.current, inChat: state.view === 'view-chat' }) })
@@ -94,3 +94,16 @@
94
94
  }
95
95
  @media(max-width:620px){.ext-page{padding:8px 0}.ext-header{margin-bottom:22px}}
96
96
  @media(prefers-reduced-motion:reduce){.ext-disclosure>summary:after{transition:none}}
97
+ .ext-shortcuts { display:flex; align-items:center; }
98
+ .ext-shortcuts-menu { position:absolute; right:10px; top:calc(100% + 4px); z-index:80; width:min(300px,calc(100vw - 20px)); max-height:min(70vh,460px); overflow-y:auto; box-sizing:border-box; padding:8px; border:1px solid var(--dsr-line); border-radius:16px; color:var(--dsr-text); background:var(--dsr-panel); box-shadow:0 14px 40px var(--dsr-shadow); text-align:left; }
99
+ .ext-shortcut-title { margin:4px 8px 8px; color:var(--dsr-muted); font-size:11px; font-weight:600; }
100
+ .ext-shortcut-item,.ext-shortcut-manage { width:100%; min-height:44px; box-sizing:border-box; padding:10px 12px; border:0; border-radius:10px; background:transparent; color:var(--dsr-text); font:inherit; font-size:14px; text-align:left; cursor:pointer; }
101
+ .ext-shortcut-item { display:grid; grid-template-columns:minmax(0,1fr) auto; gap:4px 12px; align-items:center; }
102
+ .ext-shortcut-arrow { color:var(--dsr-muted); }
103
+ .ext-shortcut-item small { grid-column:1/-1; color:var(--dsr-muted); font-size:11px; }
104
+ .ext-shortcut-item:disabled { cursor:default; opacity:.55; }
105
+ .ext-shortcut-item:not(:disabled):hover,.ext-shortcut-manage:hover { background:var(--dsr-accent-soft); }
106
+ .ext-shortcut-manage { margin-top:6px; border-top:1px solid var(--dsr-line); border-radius:0 0 10px 10px; color:var(--dsr-accent-strong); }
107
+ .ext-shortcut-empty { margin:8px; padding:10px 4px; font-size:13px; line-height:1.6; color:var(--dsr-muted); }
108
+ .ext-shortcuts :is(button):focus-visible { outline:2px solid var(--dsr-accent); outline-offset:2px; }
109
+ .ext-sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip-path:inset(50%); white-space:nowrap; border:0; }
@@ -2,6 +2,7 @@
2
2
  'use strict';
3
3
  window.DshExtensions = (() => {
4
4
  let current, cache
5
+ let shortcuts
5
6
  const catalog = [
6
7
  { id: 'skills', name: '@linxin666/dsh-client-ui-skill-explorer', label: '打开技能中心', summary: '浏览、搜索和阅读主机上的技能', verified: '0.4.6' },
7
8
  { id: 'teams', name: '@nanmicoder/dsh-agent-teams', label: '查看智能体团队', summary: '查看智能体团队、任务与成员状态', verified: '0.1.24-rc.1' },
@@ -102,8 +103,78 @@ window.DshExtensions = (() => {
102
103
  return record.task
103
104
  }
104
105
  const node=(tag,text,cls)=>{const el=document.createElement(tag);if(text!=null)el.textContent=text;if(cls)el.className=cls;return el}
106
+ const shortcutNames = { skills: ['技能中心', 'Skills'], teams: ['智能体团队', 'Agent teams'], cost: ['费用与额度', 'Costs & quotas'], context: ['上下文分析', 'Context analysis'], tasks: ['任务看板', 'Task board'] }
107
+ const shortcutText = (zh, en) => window.I18N?.lang === 'en' ? en : zh
108
+ function closeShortcuts(restoreFocus = false) {
109
+ if (!shortcuts) return
110
+ const s = shortcuts
111
+ shortcuts = null
112
+ s.menu.classList.add('hidden'); s.trigger.setAttribute('aria-expanded', 'false')
113
+ if (restoreFocus) s.trigger.focus()
114
+ return true
115
+ }
116
+ function bindShortcuts({ trigger, menu, config, connected, hasSession, open, beforeOpen }) {
117
+ if (!trigger || !menu) return
118
+ const items = () => Array.from(menu.querySelectorAll('button[role="menuitem"]:not(:disabled)'))
119
+ async function show() {
120
+ closeShortcuts(); beforeOpen?.()
121
+ const connectionConfig = config(), s = { trigger, menu, config: connectionConfig }
122
+ shortcuts = s
123
+ const valid = () => shortcuts === s && connectionConfig.valid()
124
+ const title = node('p', shortcutText('插件快捷打开', 'Plugin shortcuts'), 'ext-shortcut-title')
125
+ const list = node('div', null, 'ext-shortcut-list')
126
+ const message = text => { const p = node('p', text, 'ext-shortcut-empty'); p.setAttribute('role', 'status'); list.replaceChildren(p) }
127
+ const manage = node('button', shortcutText('插件管理', 'Manage plugins'), 'ext-shortcut-manage')
128
+ manage.type = 'button'; manage.setAttribute('role', 'menuitem')
129
+ manage.addEventListener('click', () => { if (valid()) { closeShortcuts(); open('manage') } })
130
+ menu.replaceChildren(title, list, manage)
131
+ menu.classList.remove('hidden'); trigger.setAttribute('aria-expanded', 'true')
132
+ message(connected() ? shortcutText('正在读取插件…', 'Loading plugins…') : shortcutText('请先连接 DSH 主机', 'Connect to a DSH host first'))
133
+ manage.focus()
134
+ if (!connected()) return
135
+ const available = await getCapabilities(connectionConfig)
136
+ if (!valid()) return
137
+ const features = catalog.filter(feature => available[feature.id])
138
+ if (!features.length) {
139
+ message(available.known ? shortcutText('暂无可快捷打开的插件', 'No plugin views available') : shortcutText('暂时无法读取插件,请稍后重试', 'Could not read plugins; try again'))
140
+ return
141
+ }
142
+ const focusInside = menu.contains(document.activeElement)
143
+ list.replaceChildren()
144
+ for (const feature of features) {
145
+ const button = node('button', null, 'ext-shortcut-item')
146
+ button.type = 'button'; button.setAttribute('role', 'menuitem'); button.dataset.pluginShortcut = feature.id
147
+ const label = shortcutNames[feature.id]
148
+ button.append(node('span', shortcutText(...label)), node('span', '›', 'ext-shortcut-arrow'))
149
+ if (feature.session && !hasSession()) {
150
+ button.disabled = true
151
+ button.append(node('small', shortcutText('请先打开一个会话', 'Open a session first')))
152
+ }
153
+ button.addEventListener('click', () => {
154
+ if (!valid() || (feature.session && !hasSession())) return
155
+ closeShortcuts(); open(feature.id)
156
+ })
157
+ list.append(button)
158
+ }
159
+ if (focusInside) items()[0]?.focus()
160
+ }
161
+ trigger.addEventListener('click', () => { if (shortcuts?.trigger === trigger) closeShortcuts(); else void show() })
162
+ trigger.addEventListener('keydown', event => {
163
+ if (event.key === 'ArrowDown') { event.preventDefault(); if (shortcuts?.trigger !== trigger) void show(); else items()[0]?.focus() }
164
+ })
165
+ menu.addEventListener('keydown', event => {
166
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeShortcuts(true); return }
167
+ const buttons = items(), index = buttons.indexOf(document.activeElement)
168
+ const next = event.key === 'ArrowDown' ? (index + 1) % buttons.length : event.key === 'ArrowUp' ? (index - 1 + buttons.length) % buttons.length
169
+ : event.key === 'Home' ? 0 : event.key === 'End' ? buttons.length - 1 : -1
170
+ if (next >= 0) { event.preventDefault(); buttons[next]?.focus() }
171
+ })
172
+ document.addEventListener('click', event => { if (shortcuts?.trigger === trigger && !trigger.contains(event.target) && !menu.contains(event.target)) closeShortcuts() })
173
+ document.addEventListener('focusin', event => { if (shortcuts?.trigger === trigger && !trigger.contains(event.target) && !menu.contains(event.target)) closeShortcuts() })
174
+ document.addEventListener('keydown', event => { if (shortcuts?.trigger === trigger && event.key === 'Escape') { event.preventDefault(); closeShortcuts(true) } })
175
+ }
105
176
  const stopViews=()=>{window.DshSkillsCenter?.close();window.DshInsights?.close();window.DshTeams?.close();window.DshTasks?.close()}
106
- function close(){if(current){const old=current;current=null;stopViews();window.DshPluginCenter?.close();old.target.replaceChildren()}}
177
+ function close(){closeShortcuts();if(current){const old=current;current=null;stopViews();window.DshPluginCenter?.close();old.target.replaceChildren()}}
107
178
  function mount(config,target,initial='manage') {
108
179
  close()
109
180
  const s={config,target,route:'manage',navigation:0};current=s
@@ -134,11 +205,11 @@ window.DshExtensions = (() => {
134
205
  if(valid()&&route!=='manage')config.scrollTop?.()
135
206
  }
136
207
  back.addEventListener('click',()=>{if(valid()){if(s.route==='manage')config.back?.();else void navigate('manage')}})
137
- void navigate('manage').then(()=>{if(initial!=='manage'&&initial!=='home'&&valid())void navigate(initial)})
208
+ void navigate(initial === 'home' ? 'manage' : initial)
138
209
  }
139
210
  function scrollParent(el) {
140
211
  for(let parent=el.parentElement;parent;parent=parent.parentElement)if(parent.scrollHeight>parent.clientHeight&&/auto|scroll/.test(getComputedStyle(parent).overflowY))return parent
141
212
  return document.scrollingElement
142
213
  }
143
- return {mount,close,capabilitiesOf,featuresFor,diagnosticsFor,reportAvailability,getCapabilities,remember,invalidateCapabilities,catalog:catalog.map(row=>Object.freeze({...row}))}
214
+ return {mount,close,bindShortcuts,closeShortcuts,capabilitiesOf,featuresFor,diagnosticsFor,reportAvailability,getCapabilities,remember,invalidateCapabilities,catalog:catalog.map(row=>Object.freeze({...row}))}
144
215
  })()
@@ -0,0 +1,66 @@
1
+ /* File requests share the conversation approval area. */
2
+ .session-attention { flex:0 1 auto; min-height:0; max-height:36vh; max-height:36dvh; overflow-y:auto; overscroll-behavior:contain; }
3
+ .session-attention > .session-pending,.session-attention > .ds-session-pending { max-height:none; flex:none; }
4
+ .session-attention .session-pending-list,.session-attention .ds-session-pending-list { overflow:visible; }
5
+ .file-inbox-session { margin:0 0 10px; padding:10px; border:1px solid var(--dsr-warning-line); border-radius:13px; background:var(--dsr-warning-soft); }
6
+ .file-inbox-session[hidden] { display:none !important; }
7
+ .file-inbox-files { flex:none; margin:0 0 16px; padding:14px; border:1px solid var(--dsr-line); border-radius:14px; background:var(--dsr-panel); color:var(--dsr-text); }
8
+ .file-inbox-head { display:flex; align-items:center; gap:8px; margin-bottom:8px; }
9
+ .file-inbox-head h2,.file-inbox-head h3 { flex:1; min-width:0; margin:0; color:var(--dsr-text); font-size:14px; font-weight:750; }
10
+ .file-inbox-head h3 { font-size:12px; }
11
+ .file-inbox-count { flex:none; min-width:22px; padding:2px 7px; border-radius:999px; color:var(--dsr-warning); background:var(--dsr-warning-soft); text-align:center; font-size:11px; font-weight:700; }
12
+ .file-inbox-list { display:flex; flex-direction:column; gap:8px; }
13
+ .file-inbox-card { min-width:0; padding:12px; border:1px solid var(--dsr-line); border-radius:11px; color:var(--dsr-text); background:var(--dsr-panel); overflow-wrap:anywhere; }
14
+ .file-inbox-card.needs-action { border-left:3px solid var(--dsr-warning); }
15
+ .file-inbox-files .file-inbox-card { background:var(--dsr-bg-2); }
16
+ .file-inbox-card-head { display:flex; align-items:flex-start; gap:9px; }
17
+ .file-inbox-icon { flex:none; display:grid; place-items:center; width:30px; height:34px; border:1px solid var(--dsr-warning-line); border-radius:8px; background:var(--dsr-warning-soft); color:var(--dsr-warning); font-size:20px; }
18
+ .file-inbox-names { flex:1; min-width:0; }
19
+ .file-inbox-eyebrow { display:block; margin-bottom:3px; font-size:10px; line-height:1.2; color:var(--dsr-muted); }
20
+ .file-inbox-filename { display:block; font-size:13px; line-height:1.45; font-weight:700; overflow-wrap:anywhere; }
21
+ .file-inbox-phase { flex:none; max-width:44%; margin-top:2px; padding:2px 6px; border:1px solid var(--dsr-line); border-radius:6px; color:var(--dsr-muted); font-size:10px; line-height:1.5; text-align:right; }
22
+ .file-inbox-phase.pending,.file-inbox-phase.failed { color:var(--dsr-warning); border-color:var(--dsr-warning-line); }
23
+ .file-inbox-phase.complete { color:var(--dsr-success); }
24
+ .file-inbox-meta,.file-inbox-intro,.file-inbox-empty { margin:7px 0; font-size:12px; line-height:1.5; color:var(--dsr-muted); }
25
+ .file-inbox-message { margin:6px 0; font-size:13px; line-height:1.5; white-space:pre-wrap; overflow-wrap:anywhere; }
26
+ .file-inbox-actions { display:flex; flex-wrap:wrap; gap:8px; margin-top:10px; }
27
+ .file-inbox-button { min-height:40px; padding:6px 13px; border:1px solid var(--dsr-line); border-radius:9px; background:var(--dsr-panel); color:var(--dsr-text); font:inherit; font-size:12px; cursor:pointer; }
28
+ .file-inbox-button.primary { background:var(--dsr-accent-soft); border-color:var(--dsr-accent-line); color:var(--dsr-accent-strong); font-weight:700; }
29
+ .file-inbox-button:focus-visible,.file-inbox-device input:focus-visible,.file-inbox-head h2:focus-visible { outline:2px solid var(--dsr-accent); outline-offset:2px; }
30
+ .file-inbox-button:disabled { opacity:.55; cursor:wait; }
31
+ .file-inbox-details { margin-top:6px; font-size:11px; line-height:1.5; color:var(--dsr-muted); }
32
+ .file-inbox-details summary,.file-inbox-history summary,.file-inbox-device summary { cursor:pointer; min-height:32px; align-content:center; }
33
+ .file-inbox-details p { margin:4px 0; }
34
+ .file-inbox-history,.file-inbox-device { margin-top:12px; padding-top:8px; border-top:1px solid var(--dsr-line); font-size:12px; color:var(--dsr-muted); }
35
+ .file-inbox-device input { box-sizing:border-box; max-width:100%; width:180px; min-height:40px; margin:8px 4px 8px 0; padding:6px 9px; border:1px solid var(--dsr-line); border-radius:8px; background:var(--dsr-bg-2); color:var(--dsr-text); }
36
+ .file-inbox-device small { display:block; margin-top:8px; overflow-wrap:anywhere; }
37
+ .file-inbox-note { margin:8px 0 0; color:var(--dsr-warning); font-size:12px; line-height:1.5; overflow-wrap:anywhere; }
38
+ .ds-view .file-inbox-files { margin:0 0 16px; }
39
+ .ds-view .file-inbox-session { margin:10px 22px 0; }
40
+ #view-files.ds-view { overflow-y:auto; }
41
+ @media(min-width:700px) {
42
+ .ds-view .file-inbox-card { display:grid; grid-template-columns:minmax(0,1fr) auto; column-gap:18px; }
43
+ .ds-view .file-inbox-card-head,.ds-view .file-inbox-meta,.ds-view .file-inbox-message,.ds-view .file-inbox-details { grid-column:1; }
44
+ .ds-view .file-inbox-actions { grid-column:2; grid-row:1 / 6; align-self:center; margin:0; }
45
+ .ds-view .file-inbox-note { grid-column:1 / -1; }
46
+ }
47
+ @media(max-width:360px) { .file-inbox-card { padding:10px; } .file-inbox-icon { display:none; } }
48
+ .file-inbox-card.is-compact { display:block; padding:9px 10px; }
49
+ .file-inbox-card.is-compact .file-inbox-card-head { align-items:center; gap:8px; }
50
+ .file-inbox-card.is-compact .file-inbox-filename { display:-webkit-box; -webkit-box-orient:vertical; -webkit-line-clamp:2; overflow:hidden; line-height:1.4; }
51
+ .file-inbox-inline-meta { display:flex; flex:none; flex-direction:column; align-items:flex-end; gap:2px; max-width:45%; font-size:11px; color:var(--dsr-muted); }
52
+ .file-inbox-inline-meta .file-inbox-phase { max-width:none; padding:0; margin:0; border:0; font-size:10px; }
53
+ .file-inbox-card.is-compact .file-inbox-message { display:-webkit-box; -webkit-box-orient:vertical; -webkit-line-clamp:2; overflow:hidden; margin:5px 0; line-height:1.45; font-size:12px; }
54
+ .file-inbox-card.is-compact .file-inbox-actions { margin-top:6px; gap:6px; align-items:flex-start; }
55
+ .file-inbox-card.is-compact .file-inbox-button { min-height:36px; padding:5px 11px; }
56
+ .file-inbox-card.is-compact .file-inbox-details { margin:0 0 0 auto; }
57
+ .file-inbox-card.is-compact .file-inbox-details > summary { display:flex; align-items:center; min-height:36px; padding:0 6px; list-style:none; cursor:pointer; }
58
+ .file-inbox-card.is-compact .file-inbox-details > summary::-webkit-details-marker { display:none; }
59
+ .file-inbox-card.is-compact .file-inbox-details > summary::after { content:'⌄'; margin-left:5px; }
60
+ .file-inbox-card.is-compact .file-inbox-details[open] { flex-basis:100%; order:3; }
61
+ .file-inbox-card.is-compact .file-inbox-details[open] > summary::after { content:'⌃'; }
62
+ .file-inbox-card.is-compact .file-inbox-details p { white-space:pre-wrap; }
63
+ @media(min-width:900px) {
64
+ .ds-view .session-deck[data-mounted] .file-inbox-card.is-compact[data-deck-active]:not(:has(details[open])) { display:grid !important; grid-template-columns:minmax(0,1fr) auto; column-gap:18px; }
65
+ .ds-view .file-inbox-card.is-compact .file-inbox-actions { grid-column:2; grid-row:1 / 3; align-self:center; margin:0; }
66
+ }
@@ -0,0 +1,289 @@
1
+ /* Foreground file inbox. Confirmation precedes every download; zero dependencies. */
2
+ ;(function(root) {
3
+ 'use strict'
4
+ const MAX = 50 * 1024 * 1024
5
+ const zh = () => root.I18N?.lang !== 'en'
6
+ const label = (cn, en) => zh() ? cn : en
7
+ async function hash(bytes) {
8
+ if (root.crypto?.subtle) return [...new Uint8Array(await root.crypto.subtle.digest('SHA-256', bytes))].map(n => n.toString(16).padStart(2, '0')).join('')
9
+ if (typeof root.SHA256 === 'function') return new root.SHA256().update(new Uint8Array(bytes)).hex()
10
+ throw Error(label('当前环境无法校验文件', 'File verification is unavailable'))
11
+ }
12
+ function createClient(config) {
13
+ let current = null, epoch = 0
14
+ const requests = new Set()
15
+ const stored = key => { try { return JSON.parse(root.localStorage.getItem(key) || 'null') } catch { return null } }
16
+ const persist = ctx => { if (ctx.valid()) root.localStorage.setItem(ctx.storage, JSON.stringify(ctx.prefs)) }
17
+ const requireCurrent = ctx => { if (!ctx.valid()) throw Error(label('连接已改变,请重新打开收件箱', 'Connection changed. Reopen the inbox.')) }
18
+ async function identity() {
19
+ const connection = config.capture(), generation = epoch
20
+ if (!connection.token) throw Error(label('请先连接主机', 'Connect to a host first'))
21
+ if (current?.valid()) return current
22
+ const scope = await hash(new TextEncoder().encode(config.url('/api/file-inbox') + '\0' + connection.token))
23
+ if (generation !== epoch || !connection.valid()) throw Error('connection-changed')
24
+ const storage = 'dshRemoteFileInboxV1:' + scope
25
+ let prefs = stored(storage)
26
+ if (!/^[a-f0-9]{64}$/.test(prefs?.key || '')) {
27
+ prefs = { key: [...root.crypto.getRandomValues(new Uint8Array(32))].map(n => n.toString(16).padStart(2, '0')).join(''), name: config.native?.() ? 'Android' : label('浏览器', 'Browser'), jobs: {}, receipts: {} }
28
+ }
29
+ prefs.jobs ||= {}; prefs.receipts ||= {}
30
+ const ctx = { connection, storage, prefs, lastRegister: 0, valid: () => generation === epoch && connection.valid() }
31
+ persist(ctx); current = ctx
32
+ return ctx
33
+ }
34
+ async function read(ctx, url, options, timeoutMs, decode) {
35
+ requireCurrent(ctx)
36
+ const controller = new AbortController(), timeout = AbortSignal.timeout(timeoutMs), abort = () => controller.abort()
37
+ requests.add(controller); timeout.addEventListener('abort', abort, { once: true })
38
+ try {
39
+ const response = await root.fetch(url, { ...options, signal: controller.signal, redirect: 'error' })
40
+ requireCurrent(ctx)
41
+ const data = await decode(response)
42
+ requireCurrent(ctx)
43
+ return data
44
+ } finally { requests.delete(controller); timeout.removeEventListener('abort', abort) }
45
+ }
46
+ async function api(ctx, body) {
47
+ const { response, data } = await read(ctx, config.url('/api/file-inbox'), { method: body ? 'POST' : 'GET', headers: { ...config.headers(ctx.connection), 'content-type': 'application/json', 'x-dsh-remote-inbox-key': ctx.prefs.key }, ...(body ? { body: JSON.stringify(body) } : {}) }, 12000, async response => ({ response, data: await response.json() }))
48
+ requireCurrent(ctx)
49
+ if (!response.ok) throw Error(response.status === 404 ? label('主机尚不支持文件收件箱,请升级 Remote 插件', 'Update the host Remote plugin to use the file inbox') : String(data.error || 'HTTP ' + response.status))
50
+ return data
51
+ }
52
+ async function acknowledge(ctx, id, phase) {
53
+ requireCurrent(ctx)
54
+ ctx.prefs.receipts[id] = phase; persist(ctx)
55
+ await api(ctx, { action: 'receipt', id, phase })
56
+ delete ctx.prefs.receipts[id]; persist(ctx)
57
+ }
58
+ async function sync() {
59
+ const ctx = await identity()
60
+ if (Date.now() - ctx.lastRegister > 20000) { ctx.device = await api(ctx, { action: 'register', name: ctx.prefs.name }); ctx.lastRegister = Date.now() }
61
+ const before = await api(ctx)
62
+ for (const id of Object.keys(ctx.prefs.jobs)) {
63
+ const row = before.transfers.find(row => row.id === id)
64
+ if (!row || ['expired', 'rejected', 'complete', 'downloaded'].includes(row.phase)) { delete ctx.prefs.jobs[id]; delete ctx.prefs.receipts[id]; persist(ctx) }
65
+ }
66
+ for (const id of Object.keys(ctx.prefs.receipts)) {
67
+ const row = before.transfers.find(row => row.id === id)
68
+ if (!row || ['expired', 'rejected', 'complete', 'downloaded'].includes(row.phase)) { delete ctx.prefs.receipts[id]; persist(ctx) }
69
+ }
70
+ for (const [id, job] of Object.entries(ctx.prefs.jobs)) {
71
+ requireCurrent(ctx)
72
+ let status
73
+ try { status = JSON.parse(config.native()?.getFileDownloadStatus(job)) } catch { continue }
74
+ // DownloadManager returns unknown after its record is removed. Let the
75
+ // user retry instead of retaining a job that can never finish.
76
+ if (!['complete', 'error', 'unknown'].includes(status?.phase)) continue
77
+ try { await acknowledge(ctx, id, status.phase === 'complete' ? 'complete' : 'failed'); delete ctx.prefs.jobs[id]; persist(ctx) } catch {}
78
+ }
79
+ for (const [id, phase] of Object.entries(ctx.prefs.receipts)) { try { await acknowledge(ctx, id, phase) } catch {} }
80
+ const value = await api(ctx)
81
+ return { ...value, device: ctx.device, name: ctx.prefs.name, jobs: { ...ctx.prefs.jobs } }
82
+ }
83
+ return {
84
+ sync,
85
+ reset() { epoch++; current = null; for (const request of requests) request.abort(); requests.clear() },
86
+ async rename(name) { const ctx = await identity(); requireCurrent(ctx); ctx.prefs.name = String(name).trim().slice(0, 60) || 'Remote'; persist(ctx); ctx.lastRegister = 0; return sync() },
87
+ async reject(row) { const ctx = await identity(); return api(ctx, { action: 'reject', id: row.id }) },
88
+ async receive(row) {
89
+ const ctx = await identity()
90
+ const accepted = await api(ctx, { action: 'accept', id: row.id })
91
+ requireCurrent(ctx)
92
+ const url = new URL(config.url('/fs/inbox-file'), root.location.href)
93
+ url.searchParams.set('id', row.id); url.searchParams.set('ticket', accepted.ticket)
94
+ const native = config.native?.()
95
+ try {
96
+ if (native?.downloadToDownloads && native?.getFileDownloadStatus) {
97
+ const job = native.downloadToDownloads(url.href, accepted.fileName, ctx.connection.token)
98
+ if (!/^\d+$/.test(String(job))) throw Error(label('系统下载未启动', 'System download did not start'))
99
+ ctx.prefs.jobs[row.id] = String(job); persist(ctx)
100
+ return { native: true }
101
+ }
102
+ const bytes = await read(ctx, url.href, { headers: config.headers(ctx.connection) }, 20 * 60 * 1000, async response => {
103
+ if (!response.ok || accepted.size > MAX) throw Error(label('文件下载失败', 'Download failed'))
104
+ return response.arrayBuffer()
105
+ })
106
+ requireCurrent(ctx)
107
+ if (bytes.byteLength !== accepted.size || await hash(bytes) !== accepted.sha256) throw Error(label('文件校验失败', 'File verification failed'))
108
+ requireCurrent(ctx)
109
+ return { native: false, blob: new Blob([bytes], { type: 'application/octet-stream' }), name: accepted.fileName, id: row.id, valid: ctx.valid,
110
+ handedOff: () => acknowledge(ctx, row.id, 'downloaded') }
111
+ } catch (error) {
112
+ if (ctx.valid()) { try { await acknowledge(ctx, row.id, 'failed') } catch {} }
113
+ throw error
114
+ }
115
+ },
116
+ }
117
+ }
118
+
119
+ const actionable = row => ['pending', 'accepted', 'downloading', 'failed'].includes(row.phase)
120
+ const sessionTransfers = (rows, sessionId) => sessionId ? rows.filter(row => row.sessionId === sessionId && actionable(row)) : []
121
+ let mounted
122
+ function mount(config) {
123
+ if (mounted || !root.document) return mounted
124
+ const client = createClient(config), doc = root.document
125
+ const node = (tag, text, cls) => { const el = doc.createElement(tag); if (text != null) el.textContent = text; if (cls) el.className = cls; return el }
126
+ const button = (text, action, key, primary = false) => {
127
+ const el = node('button', text, 'file-inbox-button' + (primary ? ' primary' : ''))
128
+ el.type = 'button'; el.dataset.inboxFocus = key; el.addEventListener('click', action); return el
129
+ }
130
+ const files = doc.getElementById('file-inbox-files'), session = doc.getElementById('file-inbox-session')
131
+ const slots = [files, session].filter(Boolean)
132
+ let snapshot, busy = false, polling = false, note = '', noteId = '', lastSignature = '', destroyed = false, generation = 0, revision = 0
133
+ let historyOpen = false, deviceOpen = false
134
+ const expanded = new Set(), ready = new Map()
135
+ const context = () => config.context?.() || { sessionId: '', inChat: false }
136
+ const releasePrepared = () => { ready.forEach(item => URL.revokeObjectURL(item.url)); ready.clear() }
137
+ const phases = () => ({ pending: label('等待接收', 'Awaiting acceptance'), accepted: label('准备下载', 'Preparing download'), downloading: label('下载中 / 等待回执', 'Downloading / awaiting receipt'), downloaded: label('已交给浏览器保存', 'Handed to browser'), complete: label('设备报告已保存', 'Device reports saved'), failed: label('接收失败', 'Receive failed'), rejected: label('已拒绝', 'Rejected'), expired: label('已过期', 'Expired') })
138
+ function reset() { generation++; client.reset(); snapshot = null; note = ''; noteId = ''; busy = false; polling = false; lastSignature = ''; historyOpen = false; deviceOpen = false; expanded.clear(); releasePrepared(); render() }
139
+ async function action(id, work) {
140
+ if (busy) return
141
+ const start = generation, scope = context(), active = doc.activeElement
142
+ const focusKey = slots.some(slot => slot.contains(active)) ? active?.dataset?.inboxFocus : ''
143
+ const actionRevision = ++revision
144
+ busy = true; noteId = id; note = label('处理中…', 'Working…'); render()
145
+ try { await work(); if (start !== generation) return; const value = await client.sync(); if (start !== generation) return; snapshot = value; note = ''; noteId = '' }
146
+ catch (error) { if (start === generation) note = error.message }
147
+ finally { if (start === generation) { busy = false; render(); restoreActionFocus(focusKey, scope, start, actionRevision) } }
148
+ }
149
+ function restoreActionFocus(key, scope, start, actionRevision) {
150
+ if (!key) return
151
+ // Wait for the session deck to select and reveal the replacement card.
152
+ root.requestAnimationFrame(() => {
153
+ const current = context(), active = doc.activeElement
154
+ if (destroyed || start !== generation || actionRevision !== revision || busy ||
155
+ current.sessionId !== scope.sessionId || current.inChat !== scope.inChat ||
156
+ (active && active !== doc.body && active !== doc.documentElement)) return
157
+ const visible = el => el && !el.disabled && !el.closest('[hidden],.hidden,[inert]') && el.getClientRects().length
158
+ const candidates = slots.flatMap(slot => [...slot.querySelectorAll('[data-inbox-focus]')])
159
+ const keys = [key.replace(/:accept$/, ':save'), key, key.replace(/:[^:]+$/, ':card')]
160
+ const target = keys.map(value => candidates.find(el => el.dataset.inboxFocus === value && visible(el))).find(Boolean)
161
+ || candidates.find(el => el.dataset.inboxFocus.startsWith('session:') && visible(el))
162
+ || (scope.inChat ? [doc.getElementById('session-deck-stage'), doc.getElementById('composer-input'), doc.getElementById('composer')].find(visible)
163
+ : candidates.find(el => el.dataset.inboxFocus === 'files:heading' && visible(el)))
164
+ target?.focus({ preventScroll: true })
165
+ })
166
+ }
167
+ function card(row, placement) {
168
+ const compact = placement === 'session', prepared = ready.get(row.id)
169
+ const el = node('article', null, 'file-inbox-card' + (compact ? ' is-compact' : '') + (actionable(row) ? ' needs-action' : ''))
170
+ el.dataset.transferId = row.id
171
+ const key = action => placement + ':' + row.id + ':' + action
172
+ el.tabIndex = -1; el.dataset.inboxFocus = key('card')
173
+ const head = node('div', null, 'file-inbox-card-head'), icon = node('span', '↓', 'file-inbox-icon'), names = node('div', null, 'file-inbox-names')
174
+ icon.setAttribute('aria-hidden', 'true')
175
+ const size = row.size < 1024 ? row.size + ' B' : row.size < 1048576 ? (row.size / 1024).toFixed(1) + ' KiB' : (row.size / 1048576).toFixed(2) + ' MiB'
176
+ const purpose = [row.title && row.title !== row.fileName ? row.title : '', row.message].filter(Boolean).join(' · ')
177
+ if (compact) {
178
+ names.append(node('strong', row.fileName, 'file-inbox-filename'))
179
+ const extension = /\.([a-z0-9]{1,10})$/i.exec(row.fileName)?.[1]?.toUpperCase()
180
+ const meta = node('div', null, 'file-inbox-inline-meta'); meta.append(node('span', (extension ? extension + ' · ' : '') + size, 'file-inbox-size'))
181
+ if (prepared || row.phase !== 'pending') meta.append(node('span', prepared ? label('传输校验通过', 'Transfer verified') : phases()[row.phase] || row.phase, 'file-inbox-phase ' + row.phase))
182
+ head.append(names, meta); el.append(head, node('p', purpose || label('未附文件说明', 'No file description provided'), 'file-inbox-message'))
183
+ } else {
184
+ names.append(node('span', label('文件接收请求', 'File delivery'), 'file-inbox-eyebrow'), node('strong', row.fileName, 'file-inbox-filename'))
185
+ head.append(icon, names, node('span', phases()[row.phase] || row.phase, 'file-inbox-phase ' + row.phase)); el.append(head)
186
+ el.append(node('p', size + (row.title && row.title !== row.fileName ? ' · ' + row.title : ''), 'file-inbox-meta'))
187
+ if (row.message) el.append(node('p', row.message, 'file-inbox-message'))
188
+ }
189
+ const details = node('details', null, 'file-inbox-details'); details.open = expanded.has(key('details'))
190
+ details.append(node('summary', compact ? label('详情', 'Details') : label('查看详情', 'Details')))
191
+ if (compact) details.append(node('p', label('文件:', 'File: ') + row.fileName), node('p', label('说明:', 'Description: ') + (purpose || label('未提供', 'Not provided'))))
192
+ details.append(node('p', label('来源会话:', 'Session: ') + (config.sessionTitle?.(row.sessionId) || row.sessionId)), node('p', label('到期:', 'Expires: ') + new Date(row.expiresAt).toLocaleString()))
193
+ details.addEventListener('toggle', () => details.open ? expanded.add(key('details')) : expanded.delete(key('details')))
194
+ if (!compact) el.append(details)
195
+ const actions = node('div', null, 'file-inbox-actions')
196
+ if (prepared) {
197
+ if (!compact) el.append(node('p', label('已校验,点击保存文件。', 'Verified. Save the file to continue.'), 'file-inbox-meta'))
198
+ actions.append(button(label('保存文件', 'Save file'), () => action(row.id, async () => {
199
+ if (!prepared.valid()) throw Error(label('连接已改变', 'Connection changed'))
200
+ const anchor = node('a'); anchor.href = prepared.url; anchor.download = prepared.name; doc.body.append(anchor); anchor.click(); anchor.remove()
201
+ await prepared.handedOff(); URL.revokeObjectURL(prepared.url); ready.delete(row.id)
202
+ }), key('save'), true))
203
+ } else if (actionable(row) && !snapshot.jobs?.[row.id]) {
204
+ actions.append(button(row.phase === 'pending' ? label('接收文件', 'Accept file') : label('重新接收', 'Receive again'), () => action(row.id, async () => {
205
+ const out = await client.receive(row)
206
+ if (!out.native) ready.set(row.id, { ...out, url: URL.createObjectURL(out.blob) })
207
+ }), key('accept'), true))
208
+ if (row.phase === 'pending') actions.append(button(label('拒绝', 'Reject'), () => action(row.id, () => client.reject(row)), key('reject')))
209
+ }
210
+ if (compact) actions.append(details)
211
+ if (actions.children.length) el.append(actions)
212
+ if (note && noteId === row.id) el.append(node('p', note, 'file-inbox-note'))
213
+ return el
214
+ }
215
+ function render() {
216
+ if (destroyed) return
217
+ const active = doc.activeElement, focused = active?.dataset?.inboxFocus, hadFocus = slots.some(slot => slot.contains(active))
218
+ const rows = snapshot?.transfers || [], current = context()
219
+ if (session) {
220
+ const selected = current.inChat ? sessionTransfers(rows, current.sessionId) : []
221
+ session.hidden = !selected.length
222
+ session.replaceChildren()
223
+ if (selected.length) {
224
+ const header = node('div', null, 'file-inbox-head'), heading = node('h3', label('待接收文件', 'Incoming files'))
225
+ header.append(heading, node('span', String(selected.length), 'file-inbox-count'))
226
+ const list = node('div', null, 'file-inbox-list'); for (const row of selected) list.append(card(row, 'session'))
227
+ session.append(header, list)
228
+ }
229
+ }
230
+ if (files) {
231
+ files.replaceChildren()
232
+ const header = node('header', null, 'file-inbox-head'), heading = node('h2', label('文件收件箱', 'File inbox'))
233
+ heading.tabIndex = -1; heading.dataset.inboxFocus = 'files:heading'
234
+ const count = rows.filter(actionable).length
235
+ header.append(heading, node('span', String(count), 'file-inbox-count'), button(label('刷新', 'Refresh'), tick, 'files:refresh'))
236
+ files.append(header)
237
+ files.append(node('p', label('DSH 发来的文件,确认后才会接收。', 'Files sent by DSH are downloaded only after you accept.'), 'file-inbox-intro'))
238
+ if (note && !noteId) files.append(node('p', note, 'file-inbox-note'))
239
+ const incoming = rows.filter(actionable), list = node('div', null, 'file-inbox-list')
240
+ for (const row of incoming) list.append(card(row, 'files'))
241
+ if (!incoming.length) list.append(node('p', snapshot ? label('暂无待接收文件', 'No incoming files') : label('连接主机后可接收文件', 'Connect to a host to receive files'), 'file-inbox-empty'))
242
+ files.append(list)
243
+ const history = rows.filter(row => !actionable(row))
244
+ if (history.length) {
245
+ const group = node('details', null, 'file-inbox-history'); group.open = historyOpen
246
+ group.append(node('summary', label('已处理', 'History') + ' (' + history.length + ')'))
247
+ const items = node('div', null, 'file-inbox-list'); for (const row of history) items.append(card(row, 'history'))
248
+ group.append(items); group.addEventListener('toggle', () => { historyOpen = group.open }); files.append(group)
249
+ }
250
+ if (snapshot) {
251
+ const device = node('details', null, 'file-inbox-device'); device.open = deviceOpen
252
+ device.append(node('summary', label('接收设备 · ', 'Receiving device · ') + snapshot.name))
253
+ const field = node('label', label('设备名称 ', 'Device name ')), input = node('input'); input.value = snapshot.name; input.maxLength = 60; input.dataset.inboxFocus = 'files:name'
254
+ field.append(input); device.append(field, button(label('保存名称', 'Save name'), () => action('', async () => { await client.rename(input.value) }), 'files:rename'), node('small', label('设备编号:', 'Device id: ') + (snapshot.device?.id || '—')))
255
+ device.addEventListener('toggle', () => { deviceOpen = device.open }); files.append(device)
256
+ }
257
+ }
258
+ for (const slot of slots) for (const el of slot.querySelectorAll('button,input')) el.disabled = busy
259
+ if (hadFocus && focused) {
260
+ const target = slots.flatMap(slot => [...slot.querySelectorAll('[data-inbox-focus]')]).find(el => el.dataset.inboxFocus === focused)
261
+ if (target?.tagName === 'INPUT') target.value = active.value
262
+ if (target && !target.disabled) target.focus()
263
+ }
264
+ }
265
+ async function tick() {
266
+ if (destroyed || polling || busy || doc.visibilityState === 'hidden') return
267
+ const start = generation, readRevision = revision
268
+ polling = true
269
+ try {
270
+ const next = await client.sync(), signature = JSON.stringify(next)
271
+ if (start !== generation || readRevision !== revision) return
272
+ snapshot = next; note = ''; noteId = ''
273
+ for (const [id, item] of ready) if (!next.transfers.some(row => row.id === id && row.phase === 'downloading')) { URL.revokeObjectURL(item.url); ready.delete(id) }
274
+ if (signature !== lastSignature && doc.activeElement?.tagName !== 'INPUT') { render(); lastSignature = signature }
275
+ } catch (error) { if (start === generation && readRevision === revision) { note = error.message; noteId = ''; render() } }
276
+ finally { if (start === generation) polling = false }
277
+ }
278
+ async function open() { config.openFiles?.(); render(); files?.querySelector('h2')?.focus(); await tick() }
279
+ const entries = [...doc.querySelectorAll('[data-file-inbox-open]')]
280
+ for (const el of entries) el.addEventListener('click', open)
281
+ const timer = root.setInterval(tick, 10000)
282
+ doc.addEventListener('visibilitychange', tick)
283
+ mounted = { open, render, reset, close: () => false, refresh: tick, destroy() { client.reset(); releasePrepared(); root.clearInterval(timer); doc.removeEventListener('visibilitychange', tick); for (const el of entries) el.removeEventListener('click', open); for (const slot of slots) slot.replaceChildren(); if (session) session.hidden = true; destroyed = true; mounted = null } }
284
+ render(); void tick()
285
+ return mounted
286
+ }
287
+ root.DshFileInbox = { createClient, sessionTransfers, mount, reset: () => mounted?.reset(), refresh: () => mounted?.refresh(), render: () => mounted?.render(), open: () => mounted?.open(), close: () => mounted?.close() }
288
+ if (typeof module !== 'undefined') module.exports = root.DshFileInbox
289
+ })(typeof window !== 'undefined' ? window : globalThis)