@hyprnos/dsh-remote-plugin 0.0.0-stage → 0.8.9

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.
Files changed (211) hide show
  1. package/README.en.md +61 -0
  2. package/README.md +60 -2
  3. package/apk/dsh-remote.apk +0 -0
  4. package/approval-summary.mjs +115 -0
  5. package/client.js +197 -0
  6. package/cordis.patch.yml +5 -0
  7. package/doctor-skill.mjs +99 -0
  8. package/doctor-target.mjs +24 -0
  9. package/file-delivery.mjs +84 -0
  10. package/gateway-stats.cjs +501 -0
  11. package/gateway.cjs +8451 -0
  12. package/index.mjs +1788 -0
  13. package/insights.mjs +111 -0
  14. package/market.mjs +86 -0
  15. package/package.json +73 -4
  16. package/peak-reminders.mjs +50 -0
  17. package/plugin-center.mjs +777 -0
  18. package/plugin-transaction.mjs +300 -0
  19. package/public/activity.js +188 -0
  20. package/public/admin.html +820 -0
  21. package/public/admin.js +1167 -0
  22. package/public/announcement-forms.js +89 -0
  23. package/public/announcements.json +464 -0
  24. package/public/app.js +8826 -0
  25. package/public/approval-records.js +301 -0
  26. package/public/approval-summary.js +78 -0
  27. package/public/build.json +5 -0
  28. package/public/cache-upgrade.js +51 -0
  29. package/public/chat-copy.js +59 -0
  30. package/public/chat-files.js +87 -0
  31. package/public/desktop/desktop.css +816 -0
  32. package/public/desktop/desktop.html +871 -0
  33. package/public/desktop/desktop.js +4548 -0
  34. package/public/desktop/i18n.js +85 -0
  35. package/public/diagnostics.js +203 -0
  36. package/public/doctor-entry.js +94 -0
  37. package/public/doctor.css +205 -0
  38. package/public/doctor.js +769 -0
  39. package/public/donate.png +0 -0
  40. package/public/e2ee-transport.js +219 -0
  41. package/public/extensions.css +109 -0
  42. package/public/extensions.js +215 -0
  43. package/public/file-inbox.css +66 -0
  44. package/public/file-inbox.js +289 -0
  45. package/public/genui.css +8 -0
  46. package/public/genui.js +254 -0
  47. package/public/history.js +304 -0
  48. package/public/i18n.js +57 -0
  49. package/public/icon.svg +12 -0
  50. package/public/image-cache.js +141 -0
  51. package/public/image-preview.js +290 -0
  52. package/public/index.html +1568 -0
  53. package/public/insights.css +28 -0
  54. package/public/insights.js +290 -0
  55. package/public/jsqr.min.js +10104 -0
  56. package/public/lan-discovery.js +94 -0
  57. package/public/link-check.js +109 -0
  58. package/public/manifest.webmanifest +16 -0
  59. package/public/md.js +333 -0
  60. package/public/morphicons-init.js +41 -0
  61. package/public/motion.js +557 -0
  62. package/public/network.js +100 -0
  63. package/public/onboarding.css +36 -0
  64. package/public/onboarding.js +253 -0
  65. package/public/operations.js +141 -0
  66. package/public/permission-presets.js +159 -0
  67. package/public/plugin-center.css +120 -0
  68. package/public/plugin-center.js +666 -0
  69. package/public/plugin-icon.svg +5 -0
  70. package/public/plugin.html +68 -0
  71. package/public/plugin.js +211 -0
  72. package/public/qrcode.min.js +2297 -0
  73. package/public/relay-autopair.js +251 -0
  74. package/public/relay-devices.js +80 -0
  75. package/public/relay-settings.css +24 -0
  76. package/public/relay-settings.js +194 -0
  77. package/public/remote-state.js +27 -0
  78. package/public/remote-ui.css +148 -0
  79. package/public/remote-ui.js +243 -0
  80. package/public/session-deck.css +79 -0
  81. package/public/session-deck.js +180 -0
  82. package/public/session-presets.js +47 -0
  83. package/public/setup.css +18 -0
  84. package/public/setup.js +213 -0
  85. package/public/sha256.js +119 -0
  86. package/public/skills.css +81 -0
  87. package/public/skills.js +202 -0
  88. package/public/skins/blue-fish/DESIGN.md +24 -0
  89. package/public/skins/blue-fish/face.png +0 -0
  90. package/public/skins/blue-fish/icon-blush.png +0 -0
  91. package/public/skins/blue-fish/icon-sleep.png +0 -0
  92. package/public/skins/blue-fish/icon-smile.png +0 -0
  93. package/public/skins/blue-fish/icon-star.png +0 -0
  94. package/public/skins/blue-fish/icon-wink.png +0 -0
  95. package/public/skins/blue-fish/icon.png +0 -0
  96. package/public/skins/blue-fish/mascot.png +0 -0
  97. package/public/skins/blue-fish/pattern.png +0 -0
  98. package/public/skins/blue-fish/preview.html +12 -0
  99. package/public/skins/blue-fish/skin.css +122 -0
  100. package/public/skins/blue-fish/sparkles.svg +18 -0
  101. package/public/skins/bocchi/DESIGN.md +99 -0
  102. package/public/skins/bocchi/face.png +0 -0
  103. package/public/skins/bocchi/grain.png +0 -0
  104. package/public/skins/bocchi/icon-blush.png +0 -0
  105. package/public/skins/bocchi/icon-sleep.png +0 -0
  106. package/public/skins/bocchi/icon-smile.png +0 -0
  107. package/public/skins/bocchi/icon-star.png +0 -0
  108. package/public/skins/bocchi/icon-wink.png +0 -0
  109. package/public/skins/bocchi/icon.png +0 -0
  110. package/public/skins/bocchi/pattern-soft.png +0 -0
  111. package/public/skins/bocchi/pattern.png +0 -0
  112. package/public/skins/bocchi/preview.html +55 -0
  113. package/public/skins/bocchi/skin.css +233 -0
  114. package/public/skins/bocchi/stage-bg.png +0 -0
  115. package/public/skins/bocchi/stage-soft.png +0 -0
  116. package/public/skins/bocchi/stand.png +0 -0
  117. package/public/skins/bocchi/sticker-guitar.png +0 -0
  118. package/public/skins/kessoku/DESIGN.md +38 -0
  119. package/public/skins/kessoku/grain.png +0 -0
  120. package/public/skins/kessoku/skin.css +212 -0
  121. package/public/skins/kita/SOURCES.json +51 -0
  122. package/public/skins/kita/face.png +0 -0
  123. package/public/skins/kita/icon-live.png +0 -0
  124. package/public/skins/kita/icon-reddress.png +0 -0
  125. package/public/skins/kita/icon-seifuku.png +0 -0
  126. package/public/skins/kita/pattern.png +0 -0
  127. package/public/skins/kita/preview.html +56 -0
  128. package/public/skins/kita/skin.css +26 -0
  129. package/public/skins/kita/stand.png +0 -0
  130. package/public/skins/kita/sticker-live.png +0 -0
  131. package/public/skins/nijika/SOURCES.json +51 -0
  132. package/public/skins/nijika/face.png +0 -0
  133. package/public/skins/nijika/icon-live.png +0 -0
  134. package/public/skins/nijika/icon-reddress.png +0 -0
  135. package/public/skins/nijika/icon-seifuku.png +0 -0
  136. package/public/skins/nijika/pattern.png +0 -0
  137. package/public/skins/nijika/preview.html +56 -0
  138. package/public/skins/nijika/skin.css +25 -0
  139. package/public/skins/nijika/stand.png +0 -0
  140. package/public/skins/nijika/sticker-live.png +0 -0
  141. package/public/skins/penguin/DESIGN.md +33 -0
  142. package/public/skins/penguin/SOURCES.json +22 -0
  143. package/public/skins/penguin/aic-blueprint.svg +24 -0
  144. package/public/skins/penguin/endfield-triangles.svg +4 -0
  145. package/public/skins/penguin/face.png +0 -0
  146. package/public/skins/penguin/icon-blush.png +0 -0
  147. package/public/skins/penguin/icon-dizzy.png +0 -0
  148. package/public/skins/penguin/icon-laugh.png +0 -0
  149. package/public/skins/penguin/icon-sleep.png +0 -0
  150. package/public/skins/penguin/icon-smile.png +0 -0
  151. package/public/skins/penguin/icon-star.png +0 -0
  152. package/public/skins/penguin/icon-wink.png +0 -0
  153. package/public/skins/penguin/icon.png +0 -0
  154. package/public/skins/penguin/mascot.png +0 -0
  155. package/public/skins/penguin/pattern-night.png +0 -0
  156. package/public/skins/penguin/pattern.png +0 -0
  157. package/public/skins/penguin/preview.html +12 -0
  158. package/public/skins/penguin/skin.css +212 -0
  159. package/public/skins/ryo/SOURCES.json +51 -0
  160. package/public/skins/ryo/face.png +0 -0
  161. package/public/skins/ryo/icon-live.png +0 -0
  162. package/public/skins/ryo/icon-reddress.png +0 -0
  163. package/public/skins/ryo/icon-seifuku.png +0 -0
  164. package/public/skins/ryo/pattern.png +0 -0
  165. package/public/skins/ryo/preview.html +56 -0
  166. package/public/skins/ryo/skin.css +25 -0
  167. package/public/skins/ryo/stand.png +0 -0
  168. package/public/skins/ryo/sticker-live.png +0 -0
  169. package/public/sponsor-entry.js +21 -0
  170. package/public/styles.css +1526 -0
  171. package/public/subagents.css +61 -0
  172. package/public/subagents.js +275 -0
  173. package/public/task-board.js +109 -0
  174. package/public/teams.js +98 -0
  175. package/public/theme-picker.css +58 -0
  176. package/public/theme-vars.css +1044 -0
  177. package/public/theme.js +166 -0
  178. package/public/transcribe-core.js +74 -0
  179. package/public/turn-results.js +121 -0
  180. package/public/update.json +49 -0
  181. package/public/vendor/gsap/NOTICE.md +10 -0
  182. package/public/vendor/gsap/gsap.min.js +11 -0
  183. package/public/vendor/morphicons/LICENSE +21 -0
  184. package/public/vendor/morphicons/README.md +10 -0
  185. package/public/vendor/morphicons/controller-CXZuwJ_M.js +152 -0
  186. package/public/vendor/morphicons/dom.js +206 -0
  187. package/public/vendor/morphicons/element.js +261 -0
  188. package/public/vendor/morphicons/normalize-CYnN3Npw.js +540 -0
  189. package/public/vendor/morphicons/spring-CFHloqPP.js +623 -0
  190. package/public/version.json +3 -0
  191. package/public/voice-input.js +1151 -0
  192. package/public/workflow.css +365 -0
  193. package/public/workflow.js +419 -0
  194. package/session-file.mjs +39 -0
  195. package/skills/dsh-remote-doctor/SKILL.md +186 -0
  196. package/skills/dsh-remote-doctor/references/wiki/README.md +40 -0
  197. package/skills/dsh-remote-doctor/references/wiki/ai-guide.md +61 -0
  198. package/skills/dsh-remote-doctor/references/wiki/connection.md +76 -0
  199. package/skills/dsh-remote-doctor/references/wiki/errors.md +26 -0
  200. package/skills/dsh-remote-doctor/references/wiki/evidence.md +44 -0
  201. package/skills/dsh-remote-doctor/references/wiki/files.md +31 -0
  202. package/skills/dsh-remote-doctor/references/wiki/maintenance.md +30 -0
  203. package/skills/dsh-remote-doctor/references/wiki/notifications.md +33 -0
  204. package/skills/dsh-remote-doctor/references/wiki/operations.md +32 -0
  205. package/skills/dsh-remote-doctor/references/wiki/plugins.md +90 -0
  206. package/skills/dsh-remote-doctor/references/wiki/sessions.md +45 -0
  207. package/skills/dsh-remote-doctor/references/wiki/sources.md +27 -0
  208. package/skills.mjs +53 -0
  209. package/speech-whisper.mjs +705 -0
  210. package/task-board.mjs +57 -0
  211. package/teams.mjs +58 -0
@@ -0,0 +1,4548 @@
1
+ /* DSH Remote 桌面端 WebUI · 零依赖 · 只引用 --dsr-* 皮肤变量 */
2
+ 'use strict'
3
+
4
+ const I18N = window.I18N
5
+ const t = (k, v) => I18N.t(k, v)
6
+ I18N.init(window.DESKTOP_STR)
7
+
8
+ const $ = (id) => document.getElementById(id)
9
+ const LS = {
10
+ get(k, d) { try { return localStorage.getItem(k) ?? d } catch { return d } },
11
+ set(k, v) { try { localStorage.setItem(k, v); return true } catch(error) { try { globalThis.DshDiagnostics?.storageFailure(k,error) } catch {} return false } },
12
+ del(k) { try { localStorage.removeItem(k) } catch {} }
13
+ }
14
+ const CLIENT_ID = (() => {
15
+ try {
16
+ const key = 'dshRemoteClientIdV2'
17
+ let id = localStorage.getItem(key)
18
+ if (!id) {
19
+ id = (globalThis.crypto?.randomUUID?.() || `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`)
20
+ localStorage.setItem(key, id)
21
+ }
22
+ return id
23
+ } catch { return '' }
24
+ })()
25
+ let doctorSessionHandoff = false
26
+ function clientIdHeaders() { return CLIENT_ID ? { 'x-dsh-remote-client-id': CLIENT_ID } : {} }
27
+ const CAP = window.Capacitor || null
28
+
29
+ /* ---------------- 皮肤 ---------------- */
30
+ const THEME_META = [
31
+ { id: 'default', sw: ['#0D1117', '#21262D', '#58A6FF'] },
32
+ { id: 'dark', sw: ['#161316', '#302323', '#FFB86B'] },
33
+ { id: 'light', sw: ['#F5F7F8', '#FFFFFF', '#176B87'] },
34
+ { id: 'neutral', sw: ['#EEF1E8', '#FAFBF6', '#47643C'] },
35
+ { id: 'mono', sw: ['#050505', '#333333', '#F5F5F5'] },
36
+ { id: 'fish', sw: ['#EAF6FF', '#FFFFFF', '#2F52D0'] },
37
+ { id: 'penguin', sw: ['#EDF3FA', '#FFFFFF', '#2B6CB0'] },
38
+ { id: 'penguin-night', sw: ['#10151B', '#1A222C', '#F2C230'] },
39
+ { id: 'bocchi', sw: ['#FFD9E8', '#FFFFFF', '#D0105A'] },
40
+ { id: 'nijika', sw: ['#FFF3D5', '#FFFFFF', '#94600C'] },
41
+ { id: 'ryo', sw: ['#E9F1FA', '#FFFFFF', '#315D91'] },
42
+ { id: 'kita', sw: ['#FFE9E5', '#FFFFFF', '#B6373C'] }
43
+ ]
44
+ function themeGet() {
45
+ const v = LS.get('dshTheme', '')
46
+ return THEME_META.some(m => m.id === v) ? v : 'fish'
47
+ }
48
+ function themeApply() {
49
+ const v = themeGet()
50
+ document.documentElement.setAttribute('data-theme', v)
51
+ const meta = THEME_META.find(m => m.id === v) || THEME_META[0]
52
+ const btn = $('btn-theme')
53
+ if (btn) btn.textContent = t('ds.theme.' + meta.id)
54
+ return meta.id || 'default'
55
+ }
56
+ function themeSet(id) { LS.set('dshTheme', id); themeApply() }
57
+ themeApply()
58
+
59
+ /* ---------------- 状态 ---------------- */
60
+ function emptyDesktopHistory() {
61
+ return { seqs: new Set(), visible: [], hasMore: false, loading: false, minSeq: Infinity, partialReasoning: new Map(), loaded:false, cached:false, tailEvicted:false }
62
+ }
63
+ const state = {
64
+ token: LS.get('token', ''),
65
+ wsTicket: { token: '', server: '', value: '', expiresAt: 0 },
66
+ server: '',
67
+ servers: [], // { id, url, note, group, token }; connection identity = URL + token
68
+ groups: ['默认'],
69
+ activeGroup: '默认',
70
+ autoSelect: { '默认': true },
71
+ groupActive: { '默认': '' },
72
+ serverLatency: {}, // URL + token -> latest /health latency
73
+ gatewayHealth: {},
74
+ selectingServer: false,
75
+ sessions: [],
76
+ sessionSort: LS.get('sessionSort', 'time') === 'workspace' ? 'workspace' : 'time',
77
+ byId: new Map(),
78
+ current: null,
79
+ sessionRecovery: { status: 'idle', error: '' },
80
+ pendingProjections: new Map(),
81
+ lastStreamResyncAt: 0,
82
+ hostInfo: null,
83
+ history: emptyDesktopHistory(),
84
+ approvals: [],
85
+ approvalRecords: new Map(),
86
+ approvalRecordsServer: null,
87
+ questions: [],
88
+ queues: {},
89
+ sessionActivity: new Set(),
90
+ queueSteering: {},
91
+ compactionBootAt: Date.now(),
92
+ compactions: {},
93
+ pendingCommands: {},
94
+ compactionPollTimer: null,
95
+ compactionClockTimer: null,
96
+ sessionTurnTimes: {},
97
+ questionModal: null,
98
+ streamsOk: { mux: false, host: false },
99
+ errCount: 0,
100
+ streamInfo: {
101
+ mux: { status: 'idle', lastOpenAt: 0, lastCloseAt: 0, lastCloseCode: 0, lastCloseReason: '' },
102
+ host: { status: 'idle', lastOpenAt: 0, lastCloseAt: 0, lastCloseCode: 0, lastCloseReason: '' },
103
+ },
104
+ streamMode: 'ws', // 'ws' | 'poll'
105
+ pollSeq: { mux: 0, host: 0 },
106
+ fs: { path: null, initial: null, loaded: false, roots: [], rootIndex: 0 },
107
+ models: { loaded: false, loading: false, groups: [], current: null, failures: [] },
108
+ workspaces: [],
109
+ wb: { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false },
110
+ archivedIds: [],
111
+ view: 'sessions',
112
+ subagentSessions: {}
113
+ }
114
+
115
+ // Increment on every identity transition, including A -> B -> A and token edits.
116
+ let connectionGeneration = 0, sessionsRequest = 0, filesRequest = 0, workbenchRequest = 0
117
+ for (const key of ['server', 'token']) {
118
+ let value = state[key]
119
+ Object.defineProperty(state, key, {
120
+ enumerable: true,
121
+ get: () => value,
122
+ set(next) {
123
+ if (next === value) return
124
+ cancelHistoryLoad()
125
+ value = next; connectionGeneration++
126
+ window.DshImagePreview?.reset?.()
127
+ clearTimeout(state.refreshTimer); state.refreshTimer = null
128
+ state.sessions = []; state.byId.clear(); state.pendingProjections.clear(); state.runtimeErrors = new Map()
129
+ state.hostInfo = null
130
+ if(typeof closeStream==='function'&&typeof streamMeta!=='undefined'){closeStream('mux');closeStream('host')}
131
+ state.current = null; state.history = emptyDesktopHistory(); state.subagentSessions = {}; window.DshSubagents?.reset()
132
+ state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
133
+ state.approvals = []; state.questions = []; state.questionModal = null
134
+ state.queues = {}; state.queueSteering = {}; state.compactions = {}; state.compactionTerminals = {}; state.compactionSeqs = {}; state.compactionBootAt = Date.now(); state.pendingCommands = {}; state.sessionTurnTimes = {}
135
+ state.sessionActivity = new Set()
136
+ state.fs.path = null; state.fs.initial = null; state.fs.loaded = false; state.fs.roots = []; state.fs.rootIndex = 0
137
+ state.workspaces = []; state.archivedIds = []; state.wb = { bound: false, path: '', projects: null }
138
+ window.DshPluginCenter?.close()
139
+ window.DshInsights?.close()
140
+ window.DshExtensions?.close()
141
+ window.DshExtensions?.invalidateCapabilities()
142
+ window.DshFileInbox?.reset()
143
+ window.DshSessionDeck?.reset()
144
+ window.DshApprovalSummary?.reset()
145
+ if (typeof document !== 'undefined') document.getElementById('btn-insights')?.classList.add('hidden')
146
+ if(typeof document!=='undefined') {
147
+ const identityGeneration=connectionGeneration
148
+ queueMicrotask(()=>{if(identityGeneration===connectionGeneration&&typeof startOverviewDetection==='function')startOverviewDetection(true,true)})
149
+ document.getElementById('history')?.replaceChildren?.()
150
+ const generation=connectionGeneration
151
+ queueMicrotask(()=>{if(generation!==connectionGeneration)return;if(typeof conversationView!=='undefined')conversationView?.reset();if(!state.current&&state.view==='view-chat')showView('view-sessions');restoreCachedSessionList()})
152
+ }
153
+ if (typeof document !== 'undefined') {
154
+ for (const id of ['modal-workspace', 'modal-workbench', 'modal-question', 'modal-new-session', 'modal-rename']) document.getElementById(id)?.classList.add('hidden')
155
+ if (typeof renderNotifStack === 'function') renderNotifStack()
156
+ }
157
+ },
158
+ })
159
+ }
160
+ function captureConnection() {
161
+ const generation = connectionGeneration, server = state.server, token = state.token
162
+ return { server, token, valid: () => generation === connectionGeneration && server === state.server && token === state.token }
163
+ }
164
+
165
+ const streams = {}
166
+ let pollTimer = null
167
+ let wsRetryTimer = null
168
+ let connTickTimer = null
169
+ let reconnectInfo = null
170
+
171
+ function esc(s) { return String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])) }
172
+ function short(id) { return '…' + String(id).slice(-8) }
173
+ function fmtTime(ts) {
174
+ if (!ts) return '—'
175
+ const d = new Date(ts)
176
+ const p = n => String(n).padStart(2, '0')
177
+ return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
178
+ }
179
+ function fmtTokens(n) {
180
+ n = Number(n) || 0
181
+ if (n >= 1e6) return (n / 1e6).toFixed(n >= 1e7 ? 0 : 1) + 'M'
182
+ if (n >= 1e3) return (n / 1e3).toFixed(n >= 1e5 ? 0 : 1) + 'K'
183
+ return String(Math.round(n))
184
+ }
185
+ function fmtCost(n) { return '¥' + (Number(n) || 0).toFixed(2) }
186
+ function fmtSize(n) {
187
+ n = Number(n) || 0
188
+ if (n >= 1024 ** 3) return (n / 1024 ** 3).toFixed(2) + ' GB'
189
+ if (n >= 1024 ** 2) return (n / 1024 ** 2).toFixed(1) + ' MB'
190
+ if (n >= 1024) return (n / 1024).toFixed(1) + ' KB'
191
+ return n + ' B'
192
+ }
193
+ function toast(text, kind = '') {
194
+ const el = $('toast')
195
+ el.textContent = text
196
+ el.className = 'ds-toast ' + kind
197
+ clearTimeout(toast._t)
198
+ toast._t = setTimeout(() => el.classList.add('hidden'), 2600)
199
+ }
200
+
201
+ /* ---------------- 预设提示词 ---------------- */
202
+ const PRESETS_KEY = 'dshPromptPresets'
203
+ function readPresets() {
204
+ try {
205
+ const v = JSON.parse(LS.get(PRESETS_KEY, '[]') || '[]')
206
+ return Array.isArray(v) ? v.filter(p => p && typeof p.id === 'string' && typeof p.name === 'string' && typeof p.text === 'string') : []
207
+ } catch { return [] }
208
+ }
209
+ function renderPresetMenuDesktop() {
210
+ const btn = $('btn-preset')
211
+ const menu = $('preset-menu')
212
+ if (!btn || !menu) return
213
+ const list = readPresets()
214
+ btn.style.display = ''
215
+ menu.classList.add('hidden')
216
+ if (!list.length) {
217
+ menu.innerHTML = `<div class="ds-empty">${esc(t('ds.presetsEmpty'))}</div><div class="ds-empty ds-presets-guide">${esc(t('ds.presetsGuide'))}</div>`
218
+ return
219
+ }
220
+ menu.innerHTML = list.map(p => `<button class="ds-action-item" data-ds-preset="${esc(p.id)}">${esc(p.name)}</button>`).join('')
221
+ }
222
+ const PRESET_NAME_MAX = 20
223
+ const PRESET_TEXT_MAX = 2000
224
+ const PRESET_LIMIT = 20
225
+ function renderPresetSummary() {
226
+ const home = $('preset-count-home')
227
+ const modal = $('preset-count')
228
+ const n = readPresets().length
229
+ if (home) home.textContent = `· ${n}/${PRESET_LIMIT}`
230
+ if (modal) modal.textContent = `${n}/${PRESET_LIMIT}`
231
+ }
232
+ function writePresets(list) {
233
+ LS.set(PRESETS_KEY, JSON.stringify(list))
234
+ renderPresetSummary()
235
+ renderPresets()
236
+ renderPresetMenuDesktop()
237
+ }
238
+ function renderPresets() {
239
+ const box = $('preset-list')
240
+ if (!box) return
241
+ const list = readPresets()
242
+ renderPresetSummary()
243
+ if (!list.length) {
244
+ box.innerHTML = `<div class="ds-preset-empty">${esc(t('presets.empty'))}</div>`
245
+ return
246
+ }
247
+ box.innerHTML = list.map(p => `<div class="ds-preset-row">
248
+ <div class="ds-preset-main"><div class="ds-preset-name">${esc(p.name)}</div><div class="ds-preset-preview">${esc((p.text || '').slice(0, 60))}</div></div>
249
+ <button class="ds-mini-btn" data-preset-edit="${esc(p.id)}">${t('presets.edit')}</button>
250
+ <button class="ds-mini-btn" data-preset-del="${esc(p.id)}">${t('presets.delete')}</button>
251
+ </div>`).join('')
252
+ box.querySelectorAll('[data-preset-edit]').forEach(b => b.addEventListener('click', () => editPreset(b.dataset.presetEdit)))
253
+ box.querySelectorAll('[data-preset-del]').forEach(b => b.addEventListener('click', () => deletePreset(b.dataset.presetDel)))
254
+ }
255
+ function promptPreset(id) {
256
+ const list = readPresets()
257
+ const existing = id ? list.find(p => p.id === id) : null
258
+ const name = prompt(t('presets.namePrompt'), existing?.name || '')
259
+ if (name == null) return
260
+ const text = prompt(t('presets.textPrompt'), existing?.text || '')
261
+ if (text == null) return
262
+ const n = (name || '').trim()
263
+ if (!n) return toast(t('presets.nameEmpty'), 'err')
264
+ if (n.length > PRESET_NAME_MAX) return toast(t('presets.nameTooLong'), 'err')
265
+ if (text.length > PRESET_TEXT_MAX) return toast(t('presets.textTooLong'), 'err')
266
+ if (existing) {
267
+ existing.name = n
268
+ existing.text = text
269
+ } else {
270
+ if (list.length >= PRESET_LIMIT) return toast(t('presets.limit'), 'err')
271
+ list.push({ id: 'p' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), name: n, text })
272
+ }
273
+ writePresets(list)
274
+ toast(existing ? t('presets.saved') : t('presets.added'), 'ok')
275
+ }
276
+ function addPreset() { promptPreset(null) }
277
+ function editPreset(id) { promptPreset(id) }
278
+ function deletePreset(id) {
279
+ const list = readPresets()
280
+ const p = list.find(x => x.id === id)
281
+ if (!p) return
282
+ if (!confirm(t('presets.confirmDelete', { name: p.name }))) return
283
+ writePresets(list.filter(x => x.id !== id))
284
+ toast(t('presets.deleted'), 'ok')
285
+ }
286
+ function openPresetModal() {
287
+ renderPresets()
288
+ const modal = $('modal-presets')
289
+ if (modal) modal.classList.remove('hidden')
290
+ }
291
+ function closePresetModal() {
292
+ const modal = $('modal-presets')
293
+ if (modal) modal.classList.add('hidden')
294
+ }
295
+ function togglePresetMenuDesktop() {
296
+ const menu = $('preset-menu')
297
+ if (!menu) return
298
+ menu.classList.toggle('hidden')
299
+ }
300
+ function toggleCmdMenuDesktop() {
301
+ const menu = $('cmd-menu')
302
+ if (!menu) return
303
+ const willOpen = menu.classList.contains('hidden')
304
+ if (willOpen) void refreshPermissionPresetsDesktop()
305
+ menu.classList.toggle('hidden', !willOpen)
306
+ }
307
+
308
+ /* 主机权限模式(沙箱+审批捆绑)目录;直接列在“指令”菜单里,旧主机回退三种沙箱模式。 */
309
+ function currentPermissionPreset() {
310
+ const perms = state.current ? proj(state.byId.get(state.current), 'permissions') : null
311
+ return typeof perms?.currentValue === 'string' ? perms.currentValue : ''
312
+ }
313
+ let permissionPresetRequest = 0
314
+ function refreshPermissionPresetsDesktop() {
315
+ const box = $('cmd-perm-inline')
316
+ if (!box || !window.DshPermissionPresets) return
317
+ const request = ++permissionPresetRequest
318
+ const sessionId = state.current
319
+ const permissionConnection = captureConnection()
320
+ return window.DshPermissionPresets.open({
321
+ container: box,
322
+ current: currentPermissionPreset(),
323
+ connection: permissionConnection,
324
+ currentValid: () => permissionConnection.valid() && state.current === sessionId && request === permissionPresetRequest,
325
+ rpc,
326
+ t,
327
+ toast,
328
+ request: async value => {
329
+ if (!permissionConnection.valid() || !sessionId || state.current !== sessionId || request !== permissionPresetRequest) return false
330
+ return runSlashCommand('/permission ' + value, true)
331
+ },
332
+ close: () => { $('cmd-menu')?.classList.add('hidden') },
333
+ })
334
+ }
335
+
336
+ /* ---------------- 模型 / 思考深度 ---------------- */
337
+ function toggleModelMenuDesktop() {
338
+ const menu = $('model-menu')
339
+ if (!menu) return
340
+ const willOpen = menu.classList.contains('hidden')
341
+ menu.classList.toggle('hidden', !willOpen)
342
+ if (willOpen && !state.models.loaded && !state.models.loading) loadSessionModels()
343
+ }
344
+
345
+ async function loadSessionModels() {
346
+ if (!state.current || state.models.loading) return
347
+ const connection = captureConnection(), sessionId = state.current, models = state.models
348
+ const request = models.request = (models.request || 0) + 1
349
+ const valid = () => connection.valid() && state.current === sessionId && state.models === models && models.request === request
350
+ models.loading = true
351
+ renderModelMenu()
352
+ try {
353
+ const v = await rpc('session.models', { sessionId })
354
+ if (!valid()) return
355
+ models.groups = v.groups || []
356
+ models.current = v.current || null
357
+ models.failures = v.failures || []
358
+ models.loaded = true
359
+ } catch (e) {
360
+ if (!valid()) return
361
+ if (e.message === 'AUTH') { toast(t('ds.toastAuth'), 'err'); state.models.loading = false; renderModelMenu(); return }
362
+ toast(t('models.loadFailed', { msg: e.message }), 'err')
363
+ }
364
+ state.models.loading = false
365
+ renderModelMenu()
366
+ }
367
+
368
+ function renderModelMenu() {
369
+ const box = $('model-menu')
370
+ if (!box) return
371
+ if (state.models.loading) { box.innerHTML = `<div class="ds-model-head">${t('menu.modelTitle')}</div><span>${t('models.loading')}</span>`; return }
372
+ const groups = state.models.groups || []
373
+ if (!groups.length) {
374
+ box.innerHTML = `<div class="ds-model-head">${t('menu.modelTitle')}</div><span>${(state.models.failures || []).map(f => esc(f.name) + ' ' + t('models.unavailable')).join(';') || t('models.none')}</span>`
375
+ return
376
+ }
377
+ const cur = state.models.current
378
+ box.innerHTML = `<div class="ds-model-head">${t('menu.modelTitle')}</div>` + groups.map(g => `
379
+ <div class="ds-model-group">
380
+ <div class="ds-model-provider">${esc(g.name || g.id)}</div>
381
+ <div class="ds-model-chips">${(g.models || []).map(m => {
382
+ const isCur = cur && cur.provider === g.id && cur.model === m.id
383
+ return `<button class="ds-model-chip ${isCur ? 'current' : ''}" data-model="${esc(m.id)}" data-provider="${esc(g.id)}">${esc(m.name || m.id)}</button>`
384
+ }).join('')}</div>
385
+ </div>`).join('') + `<div class="ds-model-effort-group" id="model-effort-group"><div class="ds-model-provider">${t('menu.effortTitle')}</div><div class="ds-model-chips" id="model-efforts"></div></div>`
386
+ box.querySelectorAll('[data-model]').forEach(btn =>
387
+ btn.addEventListener('click', () => selectSessionModel(btn.dataset.provider, btn.dataset.model)))
388
+ renderEffortMenu()
389
+ }
390
+
391
+ function renderEffortMenu() {
392
+ const group = $('model-effort-group')
393
+ const box = $('model-efforts')
394
+ if (!group || !box) return
395
+ const cur = state.models.current
396
+ const provider = (state.models.groups || []).find(g => g.id === cur?.provider)
397
+ const model = (provider?.models || []).find(m => m.id === cur?.model)
398
+ const { efforts, defaultEffort, custom } = reasoningEffortOptions(model)
399
+ group.classList.toggle('hidden', !cur || !efforts.length)
400
+ box.innerHTML = efforts.map(e => {
401
+ const isCur = cur?.reasoningEffort === e.id || (!cur?.reasoningEffort && e.id === defaultEffort)
402
+ return `<button class="ds-model-chip ${isCur ? 'current' : ''}" data-effort="${esc(e.id)}" title="${esc(e.description || '')}">${esc(e.name || e.id)}</button>`
403
+ }).join('') + (custom ? `<span class="ds-effort-hint">${esc(t('models.effortCustomHint'))}</span>` : '')
404
+ box.querySelectorAll('[data-effort]').forEach(btn =>
405
+ btn.addEventListener('click', () => selectSessionEffort(btn.dataset.effort)))
406
+ }
407
+
408
+ function reasoningEffortOptions(model) {
409
+ const raw = Array.isArray(model?.reasoning?.efforts) && model.reasoning.efforts.length
410
+ ? model.reasoning.efforts
411
+ : (Array.isArray(model?.reasoningEfforts) && model.reasoningEfforts.length ? model.reasoningEfforts : null)
412
+ const names = { low: t('models.effortLow'), high: t('models.effortHigh'), max: t('models.effortMax'), off: t('models.effortOff') }
413
+ if (raw) {
414
+ return {
415
+ efforts: raw.map(e => typeof e === 'string' ? { id: e, name: names[e] || e } : e),
416
+ defaultEffort: model?.reasoning?.defaultEffort,
417
+ custom: !model?.reasoning?.efforts
418
+ }
419
+ }
420
+ return { efforts: ['low', 'high', 'max'].map(id => ({ id, name: names[id] })), defaultEffort: undefined, custom: true }
421
+ }
422
+
423
+ async function selectSessionEffort(effortId) {
424
+ const cur = state.models.current
425
+ if (!state.current || !cur) return
426
+ const connection = captureConnection(), sessionId = state.current, models = state.models
427
+ const request = models.request = (models.request || 0) + 1
428
+ const v = await safeRpc('session.selectModel', {
429
+ sessionId, provider: cur.provider, model: cur.model, reasoningEffort: effortId
430
+ }, t('models.effortFailed'))
431
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
432
+ if (v?.selected) {
433
+ state.models.current = v.selected
434
+ renderEffortMenu()
435
+ toast(t('models.effortSwitched', { effort: effortId }), 'ok')
436
+ }
437
+ }
438
+
439
+ async function selectSessionModel(provider, modelId) {
440
+ if (!state.current) return
441
+ const connection = captureConnection(), sessionId = state.current, models = state.models
442
+ const request = models.request = (models.request || 0) + 1
443
+ const group = (state.models.groups || []).find(g => g.id === provider)
444
+ const model = (group?.models || []).find(m => m.id === modelId)
445
+ const payload = { sessionId, provider, model: modelId }
446
+ const effort = model?.reasoning?.defaultEffort || model?.reasoning?.efforts?.[0]?.id
447
+ if (effort) payload.reasoningEffort = effort
448
+ const v = await safeRpc('session.selectModel', payload, t('models.switchFailed'))
449
+ if (!connection.valid() || state.current !== sessionId || state.models !== models || models.request !== request) return
450
+ if (v?.selected) {
451
+ state.models.current = v.selected
452
+ renderModelMenu()
453
+ toast(t('models.switched', { model: v.selected.model }), 'ok')
454
+ }
455
+ }
456
+
457
+ /* ---------------- 反馈 ---------------- */
458
+ async function copyText(text) {
459
+ try { await navigator.clipboard.writeText(text); return true } catch {}
460
+ try {
461
+ const ta = document.createElement('textarea')
462
+ ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0'
463
+ document.body.appendChild(ta); ta.focus(); ta.select()
464
+ const ok = document.execCommand('copy')
465
+ ta.remove(); return ok
466
+ } catch { return false }
467
+ }
468
+ function doctorEnvironment() {
469
+ let report = {}
470
+ try { report = globalThis.DshDiagnostics?.report?.() || {} } catch {}
471
+ const health = activeGatewayHealth()
472
+ let online = false
473
+ try { online = navigator.onLine !== false } catch {}
474
+ return {
475
+ surface: 'Desktop web',
476
+ appVersion: report.client?.version || '',
477
+ gatewayVersion: health?.version || '',
478
+ gatewayOk: health?.ok === true,
479
+ gatewayReachable: health?.upstreamReachable,
480
+ dshVersion: state.hostInfo?.version || '',
481
+ host: currentServerEntry()?.note || state.server || location.host,
482
+ mux: state.streamsOk?.mux ? 'connected' : state.streamMode || 'unknown',
483
+ hostEvents: state.streamsOk?.host ? 'connected' : state.streamMode || 'unknown',
484
+ online,
485
+ }
486
+ }
487
+ function openDoctor() {
488
+ if (!window.DshDoctor) {
489
+ toast(t('ds.feedbackSubmitFailed', { msg: 'doctor unavailable' }), 'err')
490
+ return
491
+ }
492
+ const session = state.byId.get(state.current)
493
+ const cwd = sessionCwd(session)
494
+ const workspace = workspaceItems().find(item => item.path === cwd)
495
+ const connection=captureConnection(), accessToken=state.token
496
+ window.DshDoctor.open({
497
+ connection,
498
+ loadTarget:()=>window.DshDoctorEntry.loadTarget({url:apiUrl,headers:{authorization:'Bearer '+accessToken},connection}),
499
+ surface: 'desktop',
500
+ rpc: (method, payload) => rpc(method, payload),
501
+ openSession: async id => { await openSession(id); return connection.valid() && state.current===id && !$('view-chat').classList.contains('hidden') },
502
+ workspaceId: workspace?.workspaceId || '',
503
+ cwd: cwd || '',
504
+ environment: doctorEnvironment,
505
+ diagnostics: () => globalThis.DshDiagnostics?.report?.(),
506
+ exportDiagnostics: () => globalThis.DshDiagnostics?.download?.(),
507
+ copy: copyText,
508
+ toast,
509
+ })
510
+ }
511
+ function openFeedbackModal() {
512
+ document.querySelectorAll('#fb-chips .ds-fb-chip').forEach(b => b.classList.toggle('current', b.dataset.fbType === 'bug'))
513
+ $('fb-msg').value = ''
514
+ $('fb-contact').value = ''
515
+ $('fb-include-diagnostics').checked = false
516
+ $('fb-include-crashes').checked = false
517
+ $('fb-crash-details').open = false
518
+ updateFeedbackLength()
519
+ void loadCrashPreview()
520
+ $('modal-feedback').classList.remove('hidden')
521
+ setTimeout(() => $('fb-msg').focus(), 50)
522
+ }
523
+ function closeFeedbackModal() { $('modal-feedback').classList.add('hidden') }
524
+ function openDonateModal() {
525
+ const m = $('modal-donate')
526
+ if (m) m.classList.remove('hidden')
527
+ }
528
+ /* ---------------- 更新内容弹窗 ---------------- */
529
+ const NOTES_KEY = 'seenNotesVersion'
530
+ let notesVersion = ''
531
+ let notesPages = []
532
+ let notesPage = 0
533
+ function parseVersion(v) {
534
+ const m = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(String(v || '').trim())
535
+ if (!m) return { core: [0, 0, 0], pre: null }
536
+ return { core: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] || null }
537
+ }
538
+ function cmpVersion(a, b) {
539
+ const pa = parseVersion(a), pb = parseVersion(b)
540
+ for (let i = 0; i < 3; i++) {
541
+ const d = pa.core[i] - pb.core[i]
542
+ if (d) return d
543
+ }
544
+ if (!pa.pre && !pb.pre) return 0
545
+ if (!pa.pre) return 1
546
+ if (!pb.pre) return -1
547
+ const sa = String(pa.pre).split('.'), sb = String(pb.pre).split('.')
548
+ for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
549
+ const x = sa[i] ?? '', y = sb[i] ?? ''
550
+ if (x === y) continue
551
+ const nx = /^\d+$/.test(x), ny = /^\d+$/.test(y)
552
+ if (nx && ny) { const d = Number(x) - Number(y); if (d) return d }
553
+ else if (nx !== ny) return nx ? -1 : 1
554
+ else { const d = x.localeCompare(y); if (d) return d }
555
+ }
556
+ return 0
557
+ }
558
+ function splitNotes(notes) {
559
+ return String(notes || '').split(/[;;]/).map(s => s.trim()).filter(Boolean)
560
+ }
561
+ function renderNotesPages(items) {
562
+ const box = $('notes-pages')
563
+ if (!box) return
564
+ const pages = []
565
+ for (let i = 0; i < items.length; i += 3) pages.push(items.slice(i, i + 3))
566
+ notesPages = pages
567
+ notesPage = 0
568
+ box.innerHTML = pages.map(page => `<div class="notes-page" style="flex:0 0 100%;scroll-snap-align:start;box-sizing:border-box;min-width:0;">${page.map(item => `<div class="notes-item" style="padding:6px 0;line-height:1.5;">${esc(item)}</div>`).join('')}</div>`).join('')
569
+ box.scrollLeft = 0
570
+ updateNotesPage()
571
+ }
572
+ function renderNotesVersionPages(entries) {
573
+ const box = $('notes-pages')
574
+ if (!box) return
575
+ notesPages = entries
576
+ notesPage = 0
577
+ box.innerHTML = entries.map(entry => {
578
+ const items = splitNotes(entry.notes)
579
+ return `<div class="notes-page" style="flex:0 0 100%;scroll-snap-align:start;box-sizing:border-box;min-width:0;">
580
+ <div class="notes-version-title" style="font-weight:700;margin-bottom:6px;opacity:.9;">v${esc(entry.version)}</div>
581
+ ${items.length ? items.map(item => `<div class="notes-item" style="padding:6px 0;line-height:1.5;">${esc(item)}</div>`).join('') : `<div class="notes-item" style="padding:6px 0;line-height:1.5;">${esc(entry.notes || '')}</div>`}
582
+ </div>`
583
+ }).join('')
584
+ box.scrollLeft = 0
585
+ updateNotesPage()
586
+ }
587
+ function updateNotesPage() {
588
+ const box = $('notes-pages')
589
+ const pageEl = $('notes-page')
590
+ if (!box || !pageEl) return
591
+ const total = notesPages.length || 1
592
+ const idx = Math.min(Math.max(0, Math.round(box.scrollLeft / Math.max(1, box.clientWidth))), total - 1)
593
+ notesPage = idx
594
+ pageEl.textContent = t('ds.notesPage', { current: idx + 1, total })
595
+ }
596
+ function scrollNotes(dir) {
597
+ const box = $('notes-pages')
598
+ if (box) box.scrollBy({ left: dir * box.clientWidth, behavior: 'smooth' })
599
+ }
600
+ function openNotesModal(info) {
601
+ if (!info?.version) return
602
+ const history = Array.isArray(info.history) ? info.history.filter(h => h && typeof h.version === 'string' && typeof h.notes === 'string' && !String(h.version).includes('-rc')) : []
603
+ const latestStable = history[0]?.version || info.version
604
+ if (history.length) {
605
+ const seen = LS.get(NOTES_KEY, '')
606
+ let entries
607
+ if (seen) entries = history.filter(h => cmpVersion(h.version, seen) > 0)
608
+ else entries = history.slice(0, 3)
609
+ if (!entries.length) return
610
+ notesVersion = latestStable
611
+ const vEl = $('notes-version')
612
+ if (vEl) vEl.textContent = 'v' + latestStable
613
+ renderNotesVersionPages(entries.slice().reverse())
614
+ $('modal-notes').classList.remove('hidden')
615
+ return
616
+ }
617
+ if (String(info.version).includes('-rc')) return
618
+ if (LS.get(NOTES_KEY) === info.version) return
619
+ const items = splitNotes(info.notes)
620
+ if (!items.length) return
621
+ notesVersion = info.version
622
+ const vEl = $('notes-version')
623
+ if (vEl) vEl.textContent = 'v' + info.version
624
+ renderNotesPages(items)
625
+ $('modal-notes').classList.remove('hidden')
626
+ }
627
+ function closeNotesModal() {
628
+ $('modal-notes').classList.add('hidden')
629
+ if (notesVersion) { LS.set(NOTES_KEY, notesVersion); notesVersion = '' }
630
+ }
631
+ async function checkNotesOnStart() {
632
+ if (typeof window !== 'undefined' && window.DshWorkflow?.isMounted()) return
633
+ try {
634
+ const res = await fetch('../update.json?t=' + Date.now(), { cache: 'no-store' })
635
+ if (!res.ok || res.redirected || !String(res.headers.get('content-type') || '').includes('application/json')) return
636
+ const info = await res.json()
637
+ if (!info || typeof info !== 'object' || !info.version) return
638
+ if (typeof window !== 'undefined' && window.DshWorkflow?.isMounted()) return
639
+ openNotesModal(info)
640
+ } catch {}
641
+ }
642
+ async function loadCrashPreview() {
643
+ const generation=loadCrashPreview.generation=(loadCrashPreview.generation||0)+1
644
+ const connection=captureConnection(),preview=$('fb-crash-preview')
645
+ preview.textContent=t('ds.feedbackCrashLoading')
646
+ const selected=$('fb-include-diagnostics').checked,crashes=$('fb-include-crashes').checked
647
+ if(!selected&&!crashes){preview.textContent=I18N.lang==='en'?'Select a log option above to preview the attachment.':'勾选上方日志选项后,可在这里预览拟上传的附件。';return}
648
+ const read=async route=>{try{const response=await fetch(apiUrl(route),{headers:{authorization:'Bearer '+connection.token},signal:AbortSignal.timeout(5000),cache:'no-store'});if(!response.ok)throw Error();return await response.json()}catch{return {unavailable:true}}}
649
+ const evidence={}
650
+ if(selected){evidence.client=globalThis.DshDiagnostics?.report();evidence.gateway=await read('/diagnostics')}
651
+ if(crashes){const data=await read('/crash-logs');evidence.crashes=data.upload||data}
652
+ if(connection.valid()&&generation===loadCrashPreview.generation)preview.textContent=JSON.stringify(evidence,null,2)
653
+ }
654
+ function updateFeedbackLength() {
655
+ const length = $('fb-msg').value.trim().length, over = length > 20000
656
+ $('fb-length').textContent = I18N.lang === 'en' ? length + ' / 20000 characters' + (over ? ' — shorten before submitting; your text is preserved.' : '') : length + ' / 20000 字符' + (over ? ',请精简后提交;全文已保留。' : '')
657
+ $('fb-msg').setAttribute('aria-invalid', String(over))
658
+ $('fb-copy-draft').textContent = I18N.lang === 'en' ? 'Copy text' : '复制全文'
659
+ }
660
+ async function submitFeedback() {
661
+ const type = document.querySelector('#fb-chips .ds-fb-chip.current')?.dataset.fbType || 'bug'
662
+ const message = $('fb-msg').value.trim()
663
+ const contact = $('fb-contact').value.trim()
664
+ const includeDiagnostics = $('fb-include-diagnostics').checked
665
+ const includeCrashLogs = $('fb-include-crashes').checked
666
+ const clientDiagnostics=includeDiagnostics?globalThis.DshDiagnostics?.report():null
667
+ if (!message) { toast(t('ds.feedbackEmpty'), 'err'); return }
668
+ if (message.length > 20000) { toast(t('ds.feedbackTooLong'), 'err'); return }
669
+ const btn = $('fb-submit')
670
+ btn.disabled = true
671
+ const diagnostic=globalThis.DshDiagnostics?.start('feedback.submit')
672
+ try {
673
+ const res = await fetch(apiUrl('/feedback'), {
674
+ method: 'POST',
675
+ headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token },
676
+ body: JSON.stringify({ type, message, contact, appVersion: clientDiagnostics?.client.version||'', includeDiagnostics, includeCrashLogs,...(clientDiagnostics?{clientDiagnostics}:{}) })
677
+ })
678
+ diagnostic?.end({phase:res.ok?'complete':'failed',httpStatus:res.status})
679
+ let json = {}
680
+ try { json = await res.json() } catch {}
681
+ if (res.ok && json.ok) { closeFeedbackModal()
682
+ const saved=json.diagnostics?.saved===true&&json.diagnostics.reportId===clientDiagnostics?.reportId
683
+ toast(clientDiagnostics&&!saved?(I18N.lang==='en'?'Feedback received; complete diagnostic report not confirmed. Copy or export the local log.':'反馈已收到,但完整诊断日志未获保存确认,请复制或导出本地日志补充。'):t('ds.feedbackSubmitted'),clientDiagnostics&&!saved?'err':'ok')
684
+ }
685
+ else if (res.status === 429) { toast(t('ds.feedbackRateLimited'), 'err') }
686
+ else if (json.error === 'message too long' && Number.isSafeInteger(json.max)) { toast(I18N.lang === 'en' ? 'This gateway limits feedback to ' + json.max + ' characters. Your full text is preserved; update the host gateway.' : '当前网关正文上限为 ' + json.max + ' 字符,全文已保留;请更新主机网关。', 'err') }
687
+ else if (json.error === 'collector-message-limit') { toast(I18N.lang === 'en' ? 'The collector still limits feedback to ' + json.max + ' characters. Your full text is preserved; copy it before updating the collector.' : '收集器仍只支持 ' + json.max + ' 字符,全文已保留;可先复制全文,待收集器升级后再提交。', 'err') }
688
+ else if (json.error === 'collector-body-limit') { toast(I18N.lang === 'en' ? 'The collector rejected the request size. Your full text is preserved; copy it before updating the collector.' : '收集器请求体超限,全文已保留;请先复制,待收集器升级后再提交。', 'err') }
689
+ else if (json.error === 'feedback_service_unavailable') { toast(I18N.lang === 'en' ? 'Delivery is unconfirmed; it may have been received. Your text is preserved. Check before resubmitting.' : '发送结果未确认,可能已收到。全文已保留,请先核对,勿重复提交。', 'err') }
690
+ else if (json.error === 'feedback-content-unconfirmed') { toast(I18N.lang === 'en' ? 'The content receipt did not match. It may have been received; check before resubmitting. Your text is preserved.' : '正文保存回执不一致,可能已收到;请先核对,勿重复提交。全文已保留。', 'err') }
691
+ else { toast(t('ds.feedbackSubmitFailed', { msg: json.error || res.status }), 'err') }
692
+ } catch(error) {
693
+ diagnostic?.fail(error)
694
+ toast(I18N.lang === 'en' ? 'Delivery is unconfirmed; it may have been received. Your text is preserved. Check before resubmitting.' : '发送结果未确认,可能已收到。全文已保留,请先核对,勿重复提交。', 'err')
695
+ } finally {
696
+ btn.disabled = false
697
+ }
698
+ }
699
+ function showTip(text, anchorRect) {
700
+ const tip = $('ds-tip')
701
+ if (!tip) return
702
+ tip.textContent = text
703
+ tip.classList.remove('hidden')
704
+ const margin = 8
705
+ const tw = tip.offsetWidth
706
+ const th = tip.offsetHeight
707
+ let left = anchorRect.left + anchorRect.width / 2 - tw / 2
708
+ left = Math.max(margin, Math.min(left, window.innerWidth - tw - margin))
709
+ let top = anchorRect.top - th - 10
710
+ if (top < margin) top = anchorRect.bottom + 10
711
+ tip.style.left = left + 'px'
712
+ tip.style.top = top + 'px'
713
+ }
714
+ function hideTip() { const tip = $('ds-tip'); if (tip) tip.classList.add('hidden') }
715
+
716
+ /* ---------------- API ---------------- */
717
+ function apiUrl(path) { return (state.server || '') + path }
718
+ let wsTicketPromise = null
719
+ let wsTicketConnection = null
720
+ async function getWsTicket() {
721
+ // Only share an in-flight request; never reuse a previous handshake ticket.
722
+ if (wsTicketPromise && wsTicketConnection?.valid()) return wsTicketPromise
723
+ const connection = captureConnection()
724
+ const token = state.token
725
+ const server = state.server
726
+ const job = (async () => {
727
+ if (activeGatewayCapability('wsTicket') === false) throw Object.assign(new Error('ws ticket unsupported'), { unsupported: true })
728
+ const read = async signal => {
729
+ const res = await fetch(apiUrl('/api/ws-ticket'), {
730
+ method: 'POST',
731
+ signal,
732
+ headers: { authorization: 'Bearer ' + token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
733
+ })
734
+ if (!res.ok) throw Object.assign(new Error('ws ticket HTTP ' + res.status), { unsupported: [404, 405, 501].includes(res.status) })
735
+ return res.json()
736
+ }
737
+ const data = await (globalThis.DshNetwork?.readWithDeadline
738
+ ? globalThis.DshNetwork.readWithDeadline(read,8000)
739
+ : read(AbortSignal.timeout(8000)))
740
+ if (!connection.valid()) throw new Error('stale ws ticket')
741
+ if (!data?.ticket || !Number(data.expiresAt)) throw new Error('invalid ws ticket')
742
+ state.wsTicket = { token, server, value: data.ticket, expiresAt: Number(data.expiresAt) }
743
+ return data.ticket
744
+ })()
745
+ wsTicketPromise = job
746
+ wsTicketConnection = connection
747
+ try { return await job } finally { if (wsTicketPromise === job) { wsTicketPromise = null; wsTicketConnection = null } }
748
+ }
749
+ async function rpc(method, payload = {}, timeoutMs = 45000, cancellation = null) {
750
+ const diagnostic=globalThis.DshDiagnostics?.start('rpc',{method,sessionId:payload.sessionId,server:state.server})
751
+ try {
752
+ const opts = {
753
+ method: 'POST',
754
+ headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
755
+ body: JSON.stringify({ type: 'client-request', rpcId: uuid(), method, payload })
756
+ }
757
+ if (cancellation) opts.signal = cancellation
758
+ else if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
759
+ opts.signal = AbortSignal.timeout(timeoutMs)
760
+ }
761
+ const operation = window.DshOperations?.supports(method) && activeGatewayCapability('operations') === true
762
+ const connection = operation ? captureConnection() : null
763
+ const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
764
+ const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
765
+ diagnostic?.end({phase:'response',httpStatus:res.status})
766
+ if (res.status === 401) throw new Error('AUTH')
767
+ if (!res.ok) throw new Error('HTTP ' + res.status)
768
+ const full = await res.json()
769
+ if (!full?.result) throw new Error('bad response')
770
+ if (!full.result.ok) {
771
+ const err = full.result.error || {}
772
+ const error = new Error(err.code === 'session/migration-required' ? t('session.migrationRequired') : err.message || 'dsh error')
773
+ error.code = err.code
774
+ throw error
775
+ }
776
+ diagnostic?.end({phase:'complete'})
777
+ return full.result.value
778
+ } catch(error) { diagnostic?.fail(error);throw error }
779
+ }
780
+ async function respond(rpcId, value) {
781
+ const opts = {
782
+ method: 'POST',
783
+ headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
784
+ body: JSON.stringify({ type: 'client-response', rpcId, result: { ok: true, value } })
785
+ }
786
+ if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
787
+ opts.signal = AbortSignal.timeout(15000)
788
+ }
789
+ const res = await fetch(apiUrl('/api/respond'), opts)
790
+ if (res.status === 401) throw new Error('AUTH')
791
+ const receipt = await res.json()
792
+ return receipt?.accepted === true
793
+ }
794
+ function operationPendingHost(connection) {
795
+ try {
796
+ const url = new URL(connection?.server || '', location.href)
797
+ return url.host || location.host
798
+ } catch { return location.host }
799
+ }
800
+ // A durable write may have been applied even if the connection identity changed
801
+ // while its receipt was pending. Never drop that fact silently.
802
+ function notifyPendingOperation(error, connection) {
803
+ if (connection?.valid()) toast(error.message, 'err')
804
+ else toast(t('ds.sendUnconfirmedSwitched', { host: operationPendingHost(connection) }), 'err')
805
+ }
806
+ async function safeRpc(method, payload, errText) {
807
+ const connection = captureConnection()
808
+ try { const value = await rpc(method, payload); return connection.valid() ? value : null }
809
+ catch (e) {
810
+ if (e.operationPending) { notifyPendingOperation(e, connection); return null }
811
+ if (!connection.valid()) return null
812
+ if (e.message === 'AUTH') { toast(t('ds.toastAuth'), 'err'); return null }
813
+ toast(errText ? `${errText}:${e.message}` : e.message, 'err')
814
+ return null
815
+ }
816
+ }
817
+ let hostDescribePromise = null
818
+ let hostDescribeConnection = null
819
+ let hostDescribeRetryTimer = null
820
+ let hostDescribeFailures = 0
821
+
822
+ function scheduleHostDescribeRetryDesktop() {
823
+ if (!state.token || hostDescribeRetryTimer) return
824
+ const delays = [2000, 5000, 15000, 30000, 60000]
825
+ const delay = delays[Math.min(Math.max(0, hostDescribeFailures - 1), delays.length - 1)]
826
+ hostDescribeRetryTimer = setTimeout(() => {
827
+ hostDescribeRetryTimer = null
828
+ void refreshHostDescriptionDesktop()
829
+ }, delay)
830
+ }
831
+
832
+ async function refreshHostDescriptionDesktop({ notify = false } = {}) {
833
+ if (!state.token) return null
834
+ if (hostDescribePromise && hostDescribeConnection?.valid()) return hostDescribePromise
835
+ const connection = captureConnection()
836
+ hostDescribeConnection = connection
837
+ const job = (async () => {
838
+ try {
839
+ const host = await rpc('host.describe', {}, 5000)
840
+ if (!connection.valid()) return null
841
+ state.hostInfo = host
842
+ hostDescribeFailures = 0
843
+ if (hostDescribeRetryTimer) clearTimeout(hostDescribeRetryTimer)
844
+ hostDescribeRetryTimer = null
845
+ renderOverviewDesktop()
846
+ return host
847
+ } catch (error) {
848
+ if (!connection.valid()) return null
849
+ hostDescribeFailures++
850
+ scheduleHostDescribeRetryDesktop()
851
+ if (notify) toast(error.message === 'AUTH' ? t('ds.toastAuth') : error.message, 'err')
852
+ return null
853
+ } finally {
854
+ if (hostDescribePromise === job) { hostDescribePromise = null; hostDescribeConnection = null }
855
+ }
856
+ })()
857
+ hostDescribePromise = job
858
+ return job
859
+ }
860
+ function uuid() {
861
+ try { return crypto.randomUUID() } catch { return 'id-' + Date.now() + '-' + Math.random().toString(36).slice(2) }
862
+ }
863
+
864
+ /* ---------------- 多服务端分组管理(与 App 共用 servers-v2) ---------------- */
865
+ function newServerId() { return 's' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6) }
866
+ function ensureGroup(name) {
867
+ if (!name) name = '默认'
868
+ if (!state.groups.includes(name)) state.groups.push(name)
869
+ if (!(name in state.autoSelect)) state.autoSelect[name] = true
870
+ if (!(name in state.groupActive)) state.groupActive[name] = ''
871
+ return name
872
+ }
873
+ function groupServers(g) { return state.servers.filter(s => s.group === g) }
874
+ function activeServers() { return groupServers(state.activeGroup) }
875
+ function normalizedServerToken(token) { return typeof token === 'string' ? token.trim() : '' }
876
+ function serverIdentity(url, token) {
877
+ return `${String(url || '').replace(/\/+$/, '')}\u0000${normalizedServerToken(token)}`
878
+ }
879
+ function serverKey(server) { return serverIdentity(server?.url ?? server, server?.token) }
880
+ function serverToken(server) { return normalizedServerToken(server?.token) }
881
+ function currentServerEntry() {
882
+ return state.servers.find(s => s.url === state.server && serverToken(s) === state.token)
883
+ || state.servers.find(s => s.url === state.server)
884
+ || null
885
+ }
886
+ function setCurrentAccessToken(value) {
887
+ const token = normalizedServerToken(value)
888
+ if (!token) return false
889
+ const current = currentServerEntry()
890
+ if (current) current.token = token
891
+ state.token = token
892
+ LS.set('token', token)
893
+ saveServers()
894
+ return true
895
+ }
896
+
897
+ function migrateServersV1() {
898
+ if (LS.get('servers-v2', null) !== null) return
899
+ let arr = null
900
+ try { arr = JSON.parse(LS.get('servers', '')) } catch {}
901
+ if (!Array.isArray(arr)) {
902
+ const legacy = LS.get('server', '')
903
+ arr = legacy ? [legacy] : []
904
+ }
905
+ const urls = arr.map(s => String(s || '').trim().replace(/\/+$/, '')).filter(s => /^https?:\/\//i.test(s))
906
+ state.servers = urls.map((url, i) => ({ id: 's' + (i + 1), url, note: '', group: '默认', token: normalizedServerToken(state.token) }))
907
+ state.groups = ['默认']; state.activeGroup = '默认'
908
+ state.autoSelect = { '默认': true }; state.groupActive = { '默认': '' }
909
+ const active = LS.get('activeServer', '')
910
+ if (active === 'origin') state.server = ''
911
+ else {
912
+ const hit = state.servers.find(s => s.url === active)
913
+ state.server = hit ? hit.url : (state.servers[0]?.url || '')
914
+ state.groupActive['默认'] = hit ? hit.id : (state.servers[0]?.id || '')
915
+ }
916
+ saveServers()
917
+ }
918
+ function loadServers() {
919
+ let data = null
920
+ try { data = JSON.parse(LS.get('servers-v2', '')) } catch {}
921
+ if (!data || !Array.isArray(data.servers)) { migrateServersV1(); return }
922
+ const legacyToken = normalizedServerToken(state.token || LS.get('token', ''))
923
+ state.servers = data.servers.filter(s => s && typeof s.url === 'string').map(s => ({ id: s.id || newServerId(), url: s.url.replace(/\/+$/, ''), note: s.note || '', group: s.group || '默认', token: s.token == null ? legacyToken : normalizedServerToken(s.token) }))
924
+ state.groups = Array.isArray(data.groups) && data.groups.length ? data.groups : ['默认']
925
+ state.activeGroup = state.groups.includes(data.activeGroup) ? data.activeGroup : '默认'
926
+ state.autoSelect = data.autoSelect || {}
927
+ state.groupActive = data.groupActive || {}
928
+ ensureGroup('默认')
929
+ for (const s of state.servers) ensureGroup(s.group)
930
+ const manual = state.groupActive[state.activeGroup]
931
+ const manualSrv = manual ? state.servers.find(s => s.id === manual) : null
932
+ const selected = manualSrv || activeServers()[0]
933
+ state.server = selected?.url || ''
934
+ if (selected) {
935
+ state.token = serverToken(selected)
936
+ LS.set('token', state.token)
937
+ }
938
+ }
939
+ function saveServers() {
940
+ LS.set('servers-v2', JSON.stringify({
941
+ servers: state.servers, groups: state.groups, activeGroup: state.activeGroup,
942
+ autoSelect: state.autoSelect, groupActive: state.groupActive,
943
+ }))
944
+ }
945
+ function serverCandidates() {
946
+ const list = activeServers().map(s => ({ ...s, token: serverToken(s) }))
947
+ if (location.origin && !list.some(s => s.url === location.origin)) list.push({ id: 'origin', url: location.origin, token: state.token, origin: true })
948
+ return list
949
+ }
950
+ async function pingServer(base) {
951
+ const u = String(base || '').replace(/\/+$/, '')
952
+ if (!u) return Infinity
953
+ const t0 = performance.now()
954
+ const ctrl = new AbortController()
955
+ const timer = setTimeout(() => ctrl.abort(), 3500)
956
+ try {
957
+ const res = await fetch(u + '/health?probe=live&t=' + Date.now(), { signal: ctrl.signal, cache: 'no-store' })
958
+ if (!res.ok) return Infinity
959
+ const health = await res.json().catch(() => null)
960
+ if (health && typeof health === 'object') {
961
+ state.gatewayHealth[u] = health
962
+ renderOverviewDesktop()
963
+ }
964
+ return Math.round(performance.now() - t0)
965
+ } catch { return Infinity } finally { clearTimeout(timer) }
966
+ }
967
+ function activeGatewayCapability(name) {
968
+ const capabilities = activeGatewayHealth()?.capabilities
969
+ if (!capabilities || !Object.prototype.hasOwnProperty.call(capabilities, name)) return null
970
+ return Number(capabilities[name]) > 0
971
+ }
972
+
973
+ function activeGatewayHealth() {
974
+ const key = String(state.server || location.origin || '').replace(/\/+$/, '')
975
+ return state.gatewayHealth[key] || null
976
+ }
977
+
978
+ function dshReachable() {
979
+ const health = activeGatewayHealth()
980
+ if (health && typeof health.upstreamOk === 'boolean') return health.upstreamOk
981
+ if (health && typeof health.upstreamReachable === 'boolean') return health.upstreamReachable
982
+ return !!state.hostInfo && state.hostInfo.metadataOnly !== true
983
+ }
984
+ async function selectFastestServer({ silent = false, reconnect = true } = {}) {
985
+ const request = selectFastestServer.request = (selectFastestServer.request || 0) + 1
986
+ const connection = captureConnection(), group = state.activeGroup
987
+ const policy = JSON.stringify([state.autoSelect[group], state.groupActive[group], state.servers])
988
+ const valid = () => connection.valid() && request === selectFastestServer.request && state.activeGroup === group && policy === JSON.stringify([state.autoSelect[group], state.groupActive[group], state.servers])
989
+ state.selectingServer = true
990
+ try {
991
+ if (!silent) toast(t('ds.speedTesting'))
992
+ const candidates = serverCandidates()
993
+ let chosen = ''
994
+ let chosenToken = state.token
995
+ let best = null
996
+ let ms = Infinity
997
+ if (state.autoSelect[state.activeGroup] !== false) {
998
+ const measured = await Promise.all(candidates.map(async (server) => [server, await pingServer(server.url)]))
999
+ if (!valid()) return null
1000
+ for (const [server, latency] of measured) state.serverLatency[serverKey(server)] = latency
1001
+ best = candidates.filter(server => Number.isFinite(state.serverLatency[serverKey(server)])).sort((a, b) => state.serverLatency[serverKey(a)] - state.serverLatency[serverKey(b)])[0] || null
1002
+ const sameOrigin = best?.url === location.origin && best.origin
1003
+ chosen = best ? (sameOrigin ? '' : best.url) : (state.server || '')
1004
+ chosenToken = best ? serverToken(best) : state.token
1005
+ ms = best ? state.serverLatency[serverKey(best)] : Infinity
1006
+ } else {
1007
+ const manual = state.groupActive[state.activeGroup]
1008
+ const manualSrv = manual ? state.servers.find(s => s.id === manual) : null
1009
+ chosen = manualSrv ? manualSrv.url : (activeServers()[0]?.url || '')
1010
+ chosenToken = manualSrv ? serverToken(manualSrv) : state.token
1011
+ if (chosen) {
1012
+ const key = serverKey(manualSrv || { url: chosen, token: state.token })
1013
+ state.serverLatency[key] = await pingServer(chosen)
1014
+ ms = state.serverLatency[key]
1015
+ }
1016
+ }
1017
+ if (!valid()) return null
1018
+ if (typeof window !== 'undefined') window.DshNetwork?.observeLatency(ms)
1019
+ renderServers()
1020
+ if (chosen !== state.server || chosenToken !== state.token) {
1021
+ state.hostInfo = null
1022
+ hostDescribeFailures = 0
1023
+ if (hostDescribeRetryTimer) clearTimeout(hostDescribeRetryTimer)
1024
+ hostDescribeRetryTimer = null
1025
+ resetFsForServerDesktop()
1026
+ state.server = chosen
1027
+ state.token = chosenToken
1028
+ LS.set('token', state.token)
1029
+ if (best) { const srv = state.servers.find(s => s.id === best.id); if (srv) state.groupActive[state.activeGroup] = srv.id }
1030
+ saveServers()
1031
+ renderServers()
1032
+ if (!silent) {
1033
+ if (chosen) toast(t('ds.speedSwitched', { url: chosen, ms: Number.isFinite(ms) ? ms : 0 }), 'ok')
1034
+ }
1035
+ if (reconnect && state.token) { openStreams(); refreshSessions() }
1036
+ } else if (!silent) {
1037
+ if (best) toast(t('ds.speedAlreadyBest', { url: chosen, ms: state.serverLatency[serverKey(best)] }), 'ok')
1038
+ else if (chosen) toast(t('ds.speedManualUsing', { url: chosen, ms: Number.isFinite(ms) ? ms : '—' }), 'ok')
1039
+ else toast(t('ds.speedAllDown'), 'err')
1040
+ }
1041
+ return chosen
1042
+ } finally { if (request === selectFastestServer.request) state.selectingServer = false }
1043
+ }
1044
+
1045
+ function serverTitle(s) { return s.note || s.url }
1046
+ function renderGroupSelect() {
1047
+ const label = $('group-select-label')
1048
+ const menu = $('group-select-menu')
1049
+ if (!label || !menu) return
1050
+ label.textContent = state.activeGroup
1051
+ $('group-select-btn')?.setAttribute('aria-label', t('ds.groupsCurrentLabel', { group: state.activeGroup }))
1052
+ menu.innerHTML = state.groups.map(g => `<button type="button" class="ds-group-option ${g === state.activeGroup ? 'current' : ''}" data-group-option="${esc(g)}">${esc(g)}${g === state.activeGroup ? ' ✓' : ''}</button>`).join('')
1053
+ menu.querySelectorAll('[data-group-option]').forEach(b => b.addEventListener('click', () => {
1054
+ closeGroupMenu()
1055
+ if (b.dataset.groupOption !== state.activeGroup) switchGroup(b.dataset.groupOption)
1056
+ }))
1057
+ }
1058
+ function toggleGroupMenu() { $('group-select-menu').classList.toggle('hidden') }
1059
+ function closeGroupMenu() { $('group-select-menu').classList.add('hidden') }
1060
+
1061
+ let desktopGroupDrawerReturnFocus = null
1062
+
1063
+ function desktopGroupDrawerOpen() {
1064
+ return !$('ds-group-drawer')?.classList.contains('hidden')
1065
+ }
1066
+
1067
+ function renderDesktopGroupDrawer() {
1068
+ const trigger = $('ds-group-drawer-trigger')
1069
+ const brandGroup = $('ds-brand-group-name')
1070
+ const current = $('ds-group-drawer-current')
1071
+ const list = $('ds-group-drawer-list')
1072
+ if (brandGroup) brandGroup.textContent = state.activeGroup
1073
+ if (trigger) trigger.setAttribute('aria-label', t('ds.groupsDrawerOpen') + ':' + state.activeGroup)
1074
+ if (current) current.textContent = state.activeGroup
1075
+ if (!list) return
1076
+ list.innerHTML = state.groups.map(group => {
1077
+ const servers = groupServers(group)
1078
+ const selected = group === state.activeGroup
1079
+ return `<button type="button" class="ds-group-drawer-option ${selected ? 'current' : ''}" data-ds-quick-group="${esc(group)}" ${selected ? 'aria-current="true"' : ''}>
1080
+ <span class="ds-group-drawer-mark" aria-hidden="true"></span>
1081
+ <span class="ds-group-drawer-copy"><span class="ds-group-drawer-name">${esc(group)}</span><span class="ds-group-drawer-meta">${t('ds.groupsServerCount', { count: servers.length })}</span></span>
1082
+ <span class="ds-group-drawer-check" aria-hidden="true">${selected ? '✓' : ''}</span>
1083
+ </button>`
1084
+ }).join('')
1085
+ }
1086
+
1087
+ function openDesktopGroupDrawer() {
1088
+ const drawer = $('ds-group-drawer')
1089
+ const backdrop = $('ds-group-drawer-backdrop')
1090
+ const trigger = $('ds-group-drawer-trigger')
1091
+ if (!drawer || !backdrop || !trigger) return
1092
+ renderDesktopGroupDrawer()
1093
+ desktopGroupDrawerReturnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : trigger
1094
+ drawer.classList.remove('hidden')
1095
+ backdrop.classList.remove('hidden')
1096
+ trigger.setAttribute('aria-expanded', 'true')
1097
+ requestAnimationFrame(() => (drawer.querySelector('[data-ds-quick-group].current') || drawer.querySelector('[data-ds-quick-group]') || drawer).focus({ preventScroll: true }))
1098
+ }
1099
+
1100
+ function closeDesktopGroupDrawer({ restoreFocus = true } = {}) {
1101
+ const drawer = $('ds-group-drawer')
1102
+ const backdrop = $('ds-group-drawer-backdrop')
1103
+ const trigger = $('ds-group-drawer-trigger')
1104
+ if (!drawer || !backdrop || drawer.classList.contains('hidden')) return
1105
+ drawer.classList.add('hidden')
1106
+ backdrop.classList.add('hidden')
1107
+ trigger?.setAttribute('aria-expanded', 'false')
1108
+ if (restoreFocus) (desktopGroupDrawerReturnFocus || trigger)?.focus({ preventScroll: true })
1109
+ desktopGroupDrawerReturnFocus = null
1110
+ }
1111
+
1112
+ function keepDesktopGroupDrawerFocus(event) {
1113
+ if (!desktopGroupDrawerOpen()) return
1114
+ if (event.key === 'Escape') {
1115
+ event.preventDefault()
1116
+ closeDesktopGroupDrawer()
1117
+ return
1118
+ }
1119
+ if (event.key !== 'Tab') return
1120
+ const drawer = $('ds-group-drawer')
1121
+ const targets = [...drawer.querySelectorAll('button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])')]
1122
+ if (!targets.length) return
1123
+ const first = targets[0]
1124
+ const last = targets[targets.length - 1]
1125
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus() }
1126
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus() }
1127
+ }
1128
+
1129
+ function renderServers() {
1130
+ const box = $('server-list')
1131
+ if (!box) return
1132
+ renderGroupSelect()
1133
+ renderDesktopGroupDrawer()
1134
+ box.innerHTML = state.groups.map(g => {
1135
+ const list = groupServers(g)
1136
+ const auto = state.autoSelect[g] !== false
1137
+ const activeManual = state.groupActive[g] || ''
1138
+ return `<div class="ds-srv-group" data-group="${esc(g)}">
1139
+ <div class="ds-srv-head">
1140
+ <button class="ds-srv-name" data-group-name="${esc(g)}" title="${t('ds.groupsSwitchHint')}"><span class="ds-srv-label">${g === state.activeGroup ? '▾' : '▸'} ${esc(g)}</span><span class="ds-srv-count">${list.length}</span></button>
1141
+ <button class="ds-mini" data-speed-group="${esc(g)}" title="${t('ds.speedTest')}">⚡</button>
1142
+ <label class="ds-switch" title="${t('ds.groupsAutoSelect')}"><input type="checkbox" data-auto-group="${esc(g)}" ${auto ? 'checked' : ''}><span class="ds-slider"></span></label>
1143
+ ${g !== '默认' ? `<button class="ds-mini" data-del-group="${esc(g)}" title="${t('ds.groupsDelete')}">✕</button>` : ''}
1144
+ </div>
1145
+ <div class="ds-srv-body ${g === state.activeGroup ? '' : 'hidden'}">
1146
+ ${list.map(s => {
1147
+ const ms = state.serverLatency[serverKey(s)]
1148
+ const active = s.url === state.server && serverToken(s) === state.token
1149
+ // One status per row keeps long addresses readable.
1150
+ let badge = `<span class="ds-server-badge">${t('ds.serversUntested')}</span>`
1151
+ if (!s.token) badge = `<span class="ds-server-badge bad">${t('ds.serversTokenMissing')}</span>`
1152
+ else if (Number.isFinite(ms)) badge = `<span class="ds-server-badge ${active ? 'good' : ''}">${ms}ms${active ? t('ds.serversCurrent') : ''}</span>`
1153
+ else if (ms !== undefined) badge = `<span class="ds-server-badge bad">${t('ds.serversUnreachable')}</span>`
1154
+ else if (active) badge = `<span class="ds-server-badge good">${t('ds.serversCurrentOnly')}</span>`
1155
+ const activeInGroup = auto ? active : s.id === activeManual
1156
+ return `<div class="ds-server-row ${activeInGroup ? 'active' : ''}" data-use-server="${esc(s.id)}">
1157
+ <span class="ds-server-main"><span class="ds-server-note" title="${esc(serverTitle(s))}">${esc(serverTitle(s))}</span>${s.note ? `<span class="ds-server-url">${esc(s.url)}</span>` : ''}</span>${badge}
1158
+ <button class="ds-mini ds-server-edit" data-edit-server="${esc(s.id)}" title="${t('ds.serversEdit')}" aria-label="${t('ds.serversEdit')}">✎</button>
1159
+ <button class="ds-mini ds-server-del" data-del-server="${esc(s.id)}" aria-label="${t('ds.serversDelete')}">✕</button>
1160
+ </div>`
1161
+ }).join('') || `<div class="ds-empty">${t('ds.groupsNoServer')}</div>`}
1162
+ </div>
1163
+ </div>`
1164
+ }).join('')
1165
+ box.querySelectorAll('[data-group-name]').forEach(b => {
1166
+ b.addEventListener('click', () => switchGroup(b.dataset.groupName))
1167
+ b.addEventListener('dblclick', () => renameGroup(b.dataset.groupName))
1168
+ })
1169
+ box.querySelectorAll('[data-speed-group]').forEach(b => b.addEventListener('click', () => { state.activeGroup = b.dataset.speedGroup; saveServers(); selectFastestServer({ silent: false }) }))
1170
+ box.querySelectorAll('[data-auto-group]').forEach(chk => chk.addEventListener('change', (e) => {
1171
+ const g = e.target.dataset.autoGroup
1172
+ state.autoSelect[g] = e.target.checked
1173
+ saveServers()
1174
+ if (g === state.activeGroup) selectFastestServer({ silent: false })
1175
+ toast(t(e.target.checked ? 'ds.groupsAutoOn' : 'ds.groupsAutoOff', { group: g }), 'ok')
1176
+ }))
1177
+ box.querySelectorAll('[data-del-group]').forEach(b => b.addEventListener('click', () => deleteGroup(b.dataset.delGroup)))
1178
+ box.querySelectorAll('[data-del-server]').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); removeServer(b.dataset.delServer) }))
1179
+ box.querySelectorAll('[data-edit-server]').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); editServer(b.dataset.editServer) }))
1180
+ box.querySelectorAll('[data-use-server]').forEach(row => row.addEventListener('click', (e) => {
1181
+ if (e.target.closest('button')) return
1182
+ const id = row.dataset.useServer
1183
+ const s = state.servers.find(x => x.id === id)
1184
+ if (!s) return
1185
+ if (state.autoSelect[s.group] !== false) { editServer(id); return }
1186
+ state.groupActive[s.group] = id
1187
+ state.activeGroup = s.group
1188
+ if (state.server !== s.url) resetFsForServerDesktop()
1189
+ state.server = s.url
1190
+ state.token = serverToken(s)
1191
+ LS.set('token', state.token)
1192
+ saveServers()
1193
+ renderServers()
1194
+ toast(t('ds.serversManualSelected', { url: serverTitle(s) }), 'ok')
1195
+ if (state.token) { openStreams(); refreshSessions() }
1196
+ }))
1197
+ const cur = currentServerEntry()
1198
+ const curGroup = cur ? cur.group : state.activeGroup
1199
+ const curLabel = cur ? (cur.note || cur.url) : (state.server || t('ds.origin'))
1200
+ const curMs = cur ? state.serverLatency[serverKey(cur)] : undefined
1201
+ $('server-desc').textContent = t('ds.serversCurrentDesc', { group: curGroup, url: curLabel }) + (Number.isFinite(curMs) ? ' · ' + curMs + 'ms' : '')
1202
+ updateConn()
1203
+ }
1204
+
1205
+ async function addServer() {
1206
+ const input = $('server-input')
1207
+ let raw = (input?.value || '').trim().replace(/\/+$/, '')
1208
+ if (!raw) return toast(t('ds.serversNeedAddress'), 'err')
1209
+ try { const u = new URL(raw); if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error('bad') }
1210
+ catch { return toast(t('ds.serversBadProtocol'), 'err') }
1211
+ const token = normalizedServerToken(state.token)
1212
+ if (state.servers.some(s => serverIdentity(s.url, serverToken(s)) === serverIdentity(raw, token))) return toast(t('ds.serversDuplicate'), 'err')
1213
+ const note = (prompt(t('ds.serversPromptNote')) || '').trim()
1214
+ state.servers.push({ id: newServerId(), url: raw, note, group: state.activeGroup, token })
1215
+ saveServers()
1216
+ if (input) input.value = ''
1217
+ renderServers()
1218
+ toast(t('ds.serversAdded'), 'ok')
1219
+ if (state.token) selectFastestServer({ silent: false })
1220
+ }
1221
+ function editServer(id) {
1222
+ const s = state.servers.find(x => x.id === id)
1223
+ if (!s) return
1224
+ const raw = (prompt(t('ds.serversPromptEditUrl'), s.url) || '').trim().replace(/\/+$/, '')
1225
+ if (!raw) return
1226
+ try { const u = new URL(raw); if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error('bad') }
1227
+ catch { return toast(t('ds.serversBadProtocol'), 'err') }
1228
+ const tokenInput = prompt(t('ds.serversPromptEditToken'), '')
1229
+ if (tokenInput === null) return
1230
+ const token = normalizedServerToken(tokenInput) || serverToken(s)
1231
+ if (state.servers.some(x => x.id !== id && serverIdentity(x.url, serverToken(x)) === serverIdentity(raw, token))) return toast(t('ds.serversDuplicate'), 'err')
1232
+ const note = prompt(t('ds.serversPromptEditNote', { url: raw }), s.note || '')
1233
+ if (note === null) return
1234
+ const group = prompt(t('ds.serversPromptEditGroup'), s.group || '默认')
1235
+ if (group === null) return
1236
+ const wasActive = state.server === s.url && state.token === serverToken(s)
1237
+ const changedActiveUrl = wasActive && state.server !== raw
1238
+ s.url = raw; s.note = note.trim(); s.group = ensureGroup(group.trim() || '默认'); s.token = token
1239
+ if (wasActive) {
1240
+ if (changedActiveUrl) resetFsForServerDesktop()
1241
+ state.server = raw
1242
+ state.token = token
1243
+ LS.set('token', token)
1244
+ }
1245
+ saveServers(); renderServers(); toast(t('ds.serversEdited'), 'ok')
1246
+ if (wasActive && state.token) selectFastestServer({ silent: true })
1247
+ }
1248
+ function removeServer(id) {
1249
+ const s = state.servers.find(x => x.id === id)
1250
+ if (!s) return
1251
+ void window.DshImageCache?.clear(historyCacheScope(s.url,serverToken(s)))
1252
+ void window.DshHistory.cacheClear(historyCacheScope(s.url,serverToken(s)))
1253
+ state.servers = state.servers.filter(x => x.id !== id)
1254
+ const wasActive = state.server === s.url && state.token === serverToken(s)
1255
+ for (const g of state.groups) if (state.groupActive[g] === id) state.groupActive[g] = ''
1256
+ saveServers(); renderServers()
1257
+ if (wasActive) { toast(t('ds.serversRemovedActive')); selectFastestServer({ silent: true }) }
1258
+ }
1259
+ function switchGroup(name) {
1260
+ if (!state.groups.includes(name)) return
1261
+ state.activeGroup = name
1262
+ saveServers(); renderServers()
1263
+ toast(t('ds.groupsSwitched', { group: name }), 'ok')
1264
+ selectFastestServer({ silent: false })
1265
+ }
1266
+ function addGroup() {
1267
+ const name = (prompt(t('ds.groupsPromptAdd')) || '').trim()
1268
+ if (!name) return
1269
+ if (state.groups.includes(name)) return toast(t('ds.groupsDuplicate'), 'err')
1270
+ ensureGroup(name); state.activeGroup = name
1271
+ saveServers(); renderServers(); toast(t('ds.groupsAdded', { group: name }), 'ok')
1272
+ }
1273
+ function renameGroup(oldName) {
1274
+ if (oldName === '默认') return
1275
+ const name = (prompt(t('ds.groupsPromptRename', { group: oldName }), oldName) || '').trim()
1276
+ if (!name || name === oldName) return
1277
+ if (state.groups.includes(name)) return toast(t('ds.groupsDuplicate'), 'err')
1278
+ const idx = state.groups.indexOf(oldName)
1279
+ state.groups[idx] = name
1280
+ for (const s of state.servers) if (s.group === oldName) s.group = name
1281
+ if (state.activeGroup === oldName) state.activeGroup = name
1282
+ state.autoSelect[name] = state.autoSelect[oldName] !== false
1283
+ delete state.autoSelect[oldName]
1284
+ state.groupActive[name] = state.groupActive[oldName] || ''
1285
+ delete state.groupActive[oldName]
1286
+ saveServers(); renderServers(); toast(t('ds.groupsRenamed', { group: name }), 'ok')
1287
+ }
1288
+ function deleteGroup(name) {
1289
+ if (name === '默认') return toast(t('ds.groupsCannotDeleteDefault'), 'err')
1290
+ if (!state.groups.includes(name)) return
1291
+ if (!confirm(t('ds.groupsConfirmDelete', { group: name }))) return
1292
+ state.groups = state.groups.filter(g => g !== name)
1293
+ for (const s of state.servers) if (s.group === name) s.group = '默认'
1294
+ delete state.autoSelect[name]; delete state.groupActive[name]
1295
+ if (state.activeGroup === name) state.activeGroup = '默认'
1296
+ saveServers(); renderServers(); toast(t('ds.groupsDeleted'), 'ok')
1297
+ if (state.token) selectFastestServer({ silent: true })
1298
+ }
1299
+
1300
+ /* ---------------- 事件流 (WebSocket + 轮询降级) ---------------- */
1301
+ const streamMeta = {
1302
+ mux: { generation: 0, attempt: 0, failures: 0, retryTimer: null },
1303
+ host: { generation: 0, attempt: 0, failures: 0, retryTimer: null },
1304
+ }
1305
+
1306
+ function clearStreamTimers(ws) {
1307
+ if (!ws) return
1308
+ if (ws._retryTimer) clearTimeout(ws._retryTimer)
1309
+ ws._retryTimer = null
1310
+ }
1311
+
1312
+ function streamIsCurrent(kind, ws, generation) {
1313
+ return streams[kind] === ws && streamMeta[kind].generation === generation
1314
+ }
1315
+
1316
+ function aggregateStreamFailures() {
1317
+ state.errCount = Math.max(streamMeta.mux.failures, streamMeta.host.failures)
1318
+ }
1319
+
1320
+ function markStreamInfo(kind, patch) {
1321
+ state.streamInfo[kind] = { ...state.streamInfo[kind], ...patch }
1322
+ }
1323
+
1324
+ function allStreamsOpen() {
1325
+ return streams.mux?.readyState === WebSocket.OPEN && streams.host?.readyState === WebSocket.OPEN
1326
+ }
1327
+
1328
+ function clearStreamRetry(kind) {
1329
+ const meta = streamMeta[kind]
1330
+ if (meta.retryTimer) clearTimeout(meta.retryTimer)
1331
+ meta.retryTimer = null
1332
+ }
1333
+
1334
+ function closeStream(kind) {
1335
+ const meta = streamMeta[kind]
1336
+ clearStreamRetry(kind)
1337
+ meta.generation++
1338
+ const ws = streams[kind]
1339
+ streams[kind] = null
1340
+ state.streamsOk[kind] = false
1341
+ try { ws?.close() } catch {}
1342
+ }
1343
+
1344
+ function clearConnTick() {
1345
+ clearInterval(connTickTimer)
1346
+ connTickTimer = null
1347
+ }
1348
+
1349
+ function startConnTick() {
1350
+ if (connTickTimer) return
1351
+ connTickTimer = setInterval(() => {
1352
+ updateConn()
1353
+ if (!reconnectInfo || state.streamMode === 'poll' || !navigator.onLine ||
1354
+ (streams.mux?.readyState === WebSocket.OPEN && streams.host?.readyState === WebSocket.OPEN)) {
1355
+ clearConnTick()
1356
+ }
1357
+ }, 1000)
1358
+ }
1359
+
1360
+ function setReconnect(delay) {
1361
+ reconnectInfo = { at: Date.now() + delay }
1362
+ startConnTick()
1363
+ updateConn()
1364
+ }
1365
+
1366
+ function clearReconnect() {
1367
+ reconnectInfo = null
1368
+ clearConnTick()
1369
+ }
1370
+
1371
+ function openStreams() {
1372
+ if (!state.token) return
1373
+ if (state.streamMode !== 'poll') state.streamMode = 'ws'
1374
+ openStream('mux', onMuxFrame, true)
1375
+ openStream('host', onHostFrame, false)
1376
+ }
1377
+ function openStream(kind, handler, refreshOnOpen, isRestore, ticket = null) {
1378
+ if (!state.token) return
1379
+ if (ticket === null) {
1380
+ if (streams[kind] && [WebSocket.OPEN, WebSocket.CONNECTING].includes(streams[kind].readyState)) return
1381
+ const connection=captureConnection(), generation=streamMeta[kind].generation
1382
+ const valid=()=>connection.valid() && generation===streamMeta[kind].generation
1383
+ void getWsTicket().then((value) => {
1384
+ if (valid()) openStream(kind, handler, refreshOnOpen, isRestore, value)
1385
+ }).catch((error) => {
1386
+ // 兼容旧网关/插件副本: ticket 接口不可用时临时回退旧 token 握手。
1387
+ if (!valid()) return
1388
+ if (error.unsupported) openStream(kind, handler, refreshOnOpen, isRestore, '')
1389
+ else {
1390
+ clearStreamRetry(kind)
1391
+ const meta = streamMeta[kind]
1392
+ meta.failures++
1393
+ aggregateStreamFailures()
1394
+ if (state.streamMode !== 'poll' && meta.failures >= 3) { enterPollMode(); return }
1395
+ const delay = Math.round(Math.min(1500 * 2 ** Math.min(meta.attempt++, 6), 60000) * (0.8 + Math.random() * 0.4))
1396
+ meta.retryTimer = setTimeout(() => { meta.retryTimer = null; if (valid() && navigator.onLine) openStream(kind, handler, refreshOnOpen, isRestore) }, delay)
1397
+ setReconnect(delay)
1398
+ }
1399
+ })
1400
+ return
1401
+ }
1402
+ let base
1403
+ if (state.server) base = state.server.replace(/^http/, 'ws')
1404
+ else { const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'; base = `${proto}//${location.host}` }
1405
+ const auth = ticket ? `ticket=${encodeURIComponent(ticket)}` : `token=${encodeURIComponent(state.token)}`
1406
+ const clientId = CLIENT_ID ? `&clientId=${encodeURIComponent(CLIENT_ID)}` : ''
1407
+ const streamUrl = `${base}/api/events.${kind}?${auth}&client=web${clientId}`
1408
+ const current = streams[kind]
1409
+ if (current?._streamUrl === streamUrl &&
1410
+ (current.readyState === WebSocket.OPEN || current.readyState === WebSocket.CONNECTING)) return
1411
+ if (current && current._streamUrl !== streamUrl) {
1412
+ streamMeta[kind].attempt = 0
1413
+ streamMeta[kind].failures = 0
1414
+ aggregateStreamFailures()
1415
+ }
1416
+ closeStream(kind)
1417
+ const meta = streamMeta[kind]
1418
+ const generation = meta.generation
1419
+ const ws = new WebSocket(streamUrl)
1420
+ streams[kind] = ws
1421
+ ws._streamUrl = streamUrl
1422
+ ws._generation = generation
1423
+ ws._isRestore = !!isRestore
1424
+ ws.onopen = () => {
1425
+ if (!streamIsCurrent(kind, ws, generation)) return
1426
+ globalThis.DshDiagnostics?.record('stream.state',{channel:kind,status:'open',attempt:meta.failures})
1427
+ state.streamsOk[kind] = true
1428
+ markStreamInfo(kind, { status: 'open', lastOpenAt: Date.now(), lastCloseCode: 0, lastCloseReason: '' })
1429
+ meta.attempt = 0
1430
+ meta.failures = 0
1431
+ aggregateStreamFailures()
1432
+ clearStreamTimers(ws)
1433
+ // DSH mux/host 是只下行 WebSocket, 浏览器不能发送应用层 ping。
1434
+ // 网关负责 RFC6455 Ping/Pong, 前端只监听业务帧和 close 事件。
1435
+ if (state.streamMode === 'poll' && allStreamsOpen()) {
1436
+ stopPolling()
1437
+ state.streamMode = 'ws'
1438
+ }
1439
+ if (allStreamsOpen()) clearReconnect()
1440
+ updateConn()
1441
+ if (kind === 'mux') { state.approvals = []; state.questions = []; renderNotifStack() }
1442
+ if (refreshOnOpen) refreshSessions()
1443
+ if (allStreamsOpen()) {
1444
+ resyncAfterStreamOpen()
1445
+ void pingServer(state.server || location.origin)
1446
+ void refreshHostDescriptionDesktop()
1447
+ }
1448
+ }
1449
+ ws.onmessage = (msg) => {
1450
+ if (!streamIsCurrent(kind, ws, generation)) return
1451
+ state.streamsOk[kind] = true
1452
+ updateConn()
1453
+ try { handler(JSON.parse(msg.data)) } catch {}
1454
+ }
1455
+ ws.onclose = (event) => {
1456
+ clearStreamTimers(ws)
1457
+ if (!streamIsCurrent(kind, ws, generation)) return
1458
+ streams[kind] = null
1459
+ state.streamsOk[kind] = false
1460
+ markStreamInfo(kind, {
1461
+ status: 'closed',
1462
+ lastCloseAt: Date.now(),
1463
+ lastCloseCode: Number(event.code) || 0,
1464
+ lastCloseReason: String(event.reason || '').slice(0, 200),
1465
+ })
1466
+ globalThis.DshDiagnostics?.record('stream.state',{channel:kind,status:'closed',closeCode:Number(event.code)||0,attempt:meta.failures+1})
1467
+ meta.failures++
1468
+ aggregateStreamFailures()
1469
+ updateConn()
1470
+ if (!navigator.onLine) { clearReconnect(); return }
1471
+ // 任一通道连续失败 3 次就降级轮询;另一个通道不会清零它的失败计数。
1472
+ if (state.streamMode !== 'poll' && meta.failures >= 3) { enterPollMode(); return }
1473
+ if (state.servers.length && meta.failures % 5 === 0) setTimeout(() => selectFastestServer({ silent: true }), 300)
1474
+ // VPN/跨地域链路使用更宽松的指数退避: 1.5s 起步, 最大 60s, 带 20% 抖动。
1475
+ const attempt = meta.attempt++
1476
+ const baseDelay = Math.min(1500 * Math.pow(2, attempt), 60000)
1477
+ const delay = Math.round(baseDelay * (0.8 + Math.random() * 0.4))
1478
+ globalThis.DshDiagnostics?.record('stream.retry',{channel:kind,attempt:meta.attempt,delayMs:delay})
1479
+ setReconnect(delay)
1480
+ clearStreamRetry(kind)
1481
+ meta.retryTimer = setTimeout(() => {
1482
+ meta.retryTimer = null
1483
+ if (state.token && navigator.onLine) openStream(kind, handler, refreshOnOpen, state.streamMode === 'poll')
1484
+ }, delay)
1485
+ }
1486
+ ws.onerror = () => { try { ws.close() } catch {} }
1487
+ }
1488
+
1489
+ /* ---------------- 轮询降级模式 ---------------- */
1490
+ function enterPollMode() {
1491
+ globalThis.DshDiagnostics?.record('poll.state',{status:'poll'})
1492
+ if (state.streamMode === 'poll') return
1493
+ state.streamMode = 'poll'
1494
+ state.pollSeq = { mux: 0, host: 0 }
1495
+ state.streamsOk = { mux: false, host: false }
1496
+ closeStream('mux')
1497
+ closeStream('host')
1498
+ refreshSessions()
1499
+ startPolling()
1500
+ updateConn()
1501
+ }
1502
+
1503
+ function stopPolling() {
1504
+ pollInFlight?.stop()
1505
+ pollInFlight = null
1506
+ clearInterval(pollTimer); pollTimer = null
1507
+ clearInterval(wsRetryTimer); wsRetryTimer = null
1508
+ }
1509
+ function startPolling() {
1510
+ stopPolling()
1511
+ pollTimer = setInterval(pollOnce, 4000)
1512
+ wsRetryTimer = setInterval(tryRestoreWs, 30000)
1513
+ void pollOnce()
1514
+ }
1515
+ let pollInFlight = null
1516
+ async function pollOnce() {
1517
+ if (state.streamMode !== 'poll') return
1518
+ if (!pollInFlight) pollInFlight = new window.DshNetwork.PollLoop({
1519
+ active: () => state.streamMode === 'poll' && !!state.token,
1520
+ capture: () => { const connection = captureConnection(), cursors = state.pollSeq; return { valid: () => connection.valid() && state.pollSeq === cursors } },
1521
+ read: pollKind
1522
+ })
1523
+ return pollInFlight.tick()
1524
+ }
1525
+
1526
+ async function pollKind(kind, cancellation) {
1527
+ if (state.streamMode !== 'poll') return
1528
+ const connection = captureConnection(), cursors = state.pollSeq
1529
+ const valid = () => connection.valid() && state.streamMode === 'poll' && state.pollSeq === cursors && !cancellation?.aborted
1530
+ const since = state.pollSeq[kind] || 0
1531
+ let res, data
1532
+ try {
1533
+ const timeoutMs = window.DshNetwork?.profile().pollTimeout || 30000
1534
+ const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
1535
+ const read = async signal => {
1536
+ const response = await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000&epoch=${encodeURIComponent(cursors[kind + "Epoch"] || "")}`), { ...(signal ? { signal } : {}), headers })
1537
+ return {res:response,data:response.ok ? await response.json() : null}
1538
+ }
1539
+ let result
1540
+ if(globalThis.DshNetwork?.readWithDeadline)result=await globalThis.DshNetwork.readWithDeadline(read,timeoutMs,cancellation)
1541
+ else {
1542
+ const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(timeoutMs) : undefined
1543
+ const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
1544
+ result=await read(signal)
1545
+ }
1546
+ res=result.res;data=result.data
1547
+ } catch { return }
1548
+ if (!valid()) return
1549
+ if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
1550
+ if (!res.ok) return
1551
+ if (!valid()) return
1552
+ if (!data || !Array.isArray(data.events)) return
1553
+ 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)
1554
+ if (reset) {
1555
+ state.pollSeq[kind] = 0
1556
+ if (kind === 'mux') renderNotifStack()
1557
+ refreshSessions()
1558
+ if (state.current) void resyncCurrentSession()
1559
+ }
1560
+ if (data.epoch) cursors[kind + 'Epoch'] = data.epoch
1561
+ for (const frame of data.baseline || []) { if (kind === 'mux') onMuxFrame(frame); else onHostFrame(frame) }
1562
+ for (const item of data.events) {
1563
+ if (item.seq > (state.pollSeq[kind] || 0)) {
1564
+ state.pollSeq[kind] = item.seq
1565
+ if (kind === 'mux') onMuxFrame(item.event)
1566
+ else onHostFrame(item.event)
1567
+ }
1568
+ }
1569
+ return data.waitSupported === true ? 100 : 4000
1570
+ }
1571
+
1572
+ function tryRestoreWs() {
1573
+ if (state.streamMode !== 'poll' || !state.token) return
1574
+ // 轮询继续跑,等 WS 真正 onopen 后再切回,避免重连窗口丢事件
1575
+ if (!streams.mux && !streamMeta.mux.retryTimer) openStream('mux', onMuxFrame, true, true)
1576
+ if (!streams.host && !streamMeta.host.retryTimer) openStream('host', onHostFrame, false, true)
1577
+ }
1578
+
1579
+ /* 网络感知: 离线立刻关 WS + 显示离线, 在线立即重连 */
1580
+ window.addEventListener('offline', () => {
1581
+ clearReconnect()
1582
+ closeStream('mux')
1583
+ closeStream('host')
1584
+ if (state.streamMode === 'poll') stopPolling()
1585
+ updateConn()
1586
+ })
1587
+ window.addEventListener('online', () => {
1588
+ if (!state.token) { updateConn(); return }
1589
+ state.errCount = 0
1590
+ clearReconnect()
1591
+ recoverSessionHistory()
1592
+ openStreams()
1593
+ updateConn()
1594
+ })
1595
+ // Connection metrics also emit change; only a network type change needs recovery.
1596
+ let networkConnectionType=navigator.connection?.type||navigator.connection?.effectiveType
1597
+ navigator.connection?.addEventListener?.('change',()=>{
1598
+ const type=navigator.connection.type||navigator.connection.effectiveType
1599
+ if(type===networkConnectionType)return
1600
+ networkConnectionType=type
1601
+ if(document.visibilityState==='visible'&&state.token){recoverSessionHistory();openStreams();if(state.servers.length)void selectFastestServer({silent:true})}
1602
+ })
1603
+ document.addEventListener('visibilitychange', () => {
1604
+ if (document.visibilityState === 'visible' && state.token) { recoverSessionHistory();openStreams() }
1605
+ if (document.visibilityState === 'visible' && state.token &&
1606
+ (streams.mux?.readyState !== WebSocket.OPEN || streams.host?.readyState !== WebSocket.OPEN)) {
1607
+ repairMissingStreams()
1608
+ }
1609
+ })
1610
+
1611
+ setInterval(sessionSyncTick, 15000)
1612
+
1613
+ function onMuxFrame(full) {
1614
+ const f = full.payload
1615
+ if (!f) return
1616
+ if (f.type === 'session/reasoning') {
1617
+ if (f.sessionId === state.current) { applyReasoningBaseline(f.partialReasoning); scheduleReasoningRender() }
1618
+ return
1619
+ }
1620
+ if (f.type === 'session/event') return onSessionEvent(f.sessionId, f.event, { replay: f.replay === true })
1621
+ if (f.type === 'approval/requested') {
1622
+ state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId)
1623
+ state.approvals.push({ ...f, rpcId: full.rpcId })
1624
+ collectApprovalFrame(f)
1625
+ renderNotifStack()
1626
+ return
1627
+ }
1628
+ if (f.type === 'approval/resolved') { collectApprovalFrame(f); state.approvals = state.approvals.filter(a => a.approvalId !== f.approvalId); renderNotifStack(); return }
1629
+ if (f.type === 'question/requested') {
1630
+ state.questions = state.questions.filter(q => q.rpcId !== full.rpcId)
1631
+ state.questions.push({ ...f, rpcId: full.rpcId })
1632
+ renderNotifStack()
1633
+ return
1634
+ }
1635
+ if (f.type === 'question/resolved') {
1636
+ state.questions = state.questions.filter(q => q.rpcId !== f.questionRpcId)
1637
+ if (state.questionModal?.rpcId === f.questionRpcId) { $('modal-question').classList.add('hidden'); state.questionModal = null }
1638
+ renderNotifStack(); return
1639
+ }
1640
+ if (f.type === 'session/queue') { state.queues[f.sessionId] = f.items || []; renderQueue(); return }
1641
+ if (f.type === 'session/projection') { applyProjection(f.sessionId, f.key, f.value, f.seq); return }
1642
+ if (f.type === 'stream/error') toast(f.error?.message || 'stream error', 'err')
1643
+ if (f.type === 'session/stream-error' && f.sessionId === state.current) { const message=f.error?.code==='session/migration-required'?t('session.migrationRequired'):f.error?.message;setSessionRecovery('error',message);toast(message,'err') }
1644
+ }
1645
+ function onHostFrame(full) {
1646
+ const f = full.payload
1647
+ if (!f) return
1648
+ if (['host/session-added', 'host/session-removed', 'host/workspace-changed', 'host/workspace-removed', 'host/workspace-order-changed', 'host/archived-sessions-changed'].includes(f.type)) scheduleSessionsRefresh()
1649
+ if (f.type === 'host/session-activity') {
1650
+ const session = state.byId.get(f.sessionId)
1651
+ if (session) { session.updatedAt = Number(f.updatedAt) || Date.now(); renderSessions(); renderOverviewDesktop() }
1652
+ scheduleSessionSync(f.sessionId)
1653
+ return
1654
+ }
1655
+ if (f.type === 'host/session-status') {
1656
+ if (f.running && state.runtimeErrors?.delete(f.sessionId) && state.current === f.sessionId) renderHistory()
1657
+ const s = state.byId.get(f.sessionId)
1658
+ if (s) { s.running = f.running; if (f.running) s.error = false; if (state.current === f.sessionId) { renderSessions(); renderQueue(); updateComposerStatus() } renderOverviewDesktop() }
1659
+ if (!f.running) scheduleSessionSync(f.sessionId)
1660
+ }
1661
+ if (f.type === 'host/agent-error') {
1662
+ const s = state.byId.get(f.sessionId)
1663
+ if (s) { s.error = true; s.running = false }
1664
+ rememberRuntimeError(f.sessionId, f.message)
1665
+ if (state.current === f.sessionId) { renderQueue(); updateComposerStatus(); toast(String(f.message || ''), 'err') }
1666
+ }
1667
+ }
1668
+ function activeCompaction(sessionId = state.current) {
1669
+ const compact = state.compactions[sessionId]
1670
+ return compact?.active === true ? compact : null
1671
+ }
1672
+ function compactElapsed(startedAt) {
1673
+ const seconds = Math.max(0, Math.floor((Date.now() - Number(startedAt || Date.now())) / 1000))
1674
+ const minutes = Math.floor(seconds / 60)
1675
+ const remain = seconds % 60
1676
+ return minutes > 0 ? `${minutes}:${String(remain).padStart(2, '0')}` : `${remain}s`
1677
+ }
1678
+ function setCompactionStatus(sessionId, next) {
1679
+ state.compactionTerminals ||= {}
1680
+ if (!sessionId) return
1681
+ const previous = state.compactions[sessionId]
1682
+ if (next?.active === true) {
1683
+ state.compactions[sessionId] = {
1684
+ active: true,
1685
+ phase: next.phase || previous?.phase || 'running',
1686
+ command: String(next.command || previous?.command || 'compact'),
1687
+ startedAt: Number(next.startedAt) || previous?.startedAt || Date.now(),
1688
+ message: String(next.message || ''),
1689
+ source: next.source || previous?.source || 'event',
1690
+ compactionId: next.compactionId || previous?.compactionId || '',
1691
+ notify: next.notify ?? previous?.notify ?? (next.source === 'command'),
1692
+ }
1693
+ } else {
1694
+ delete state.compactions[sessionId]
1695
+ if (previous?.active) {
1696
+ state.compactionTerminals[sessionId] = { startedAt: previous.startedAt, compactionId: previous.compactionId }
1697
+ }
1698
+ if (previous?.active && previous.notify && next?.notify !== false && ['complete', 'failed'].includes(next?.phase)) {
1699
+ const command = previous.command || 'compact'
1700
+ if (command === 'export' && next?.phase === 'complete' && state.current === sessionId && typeof downloadSessionExport === 'function') void downloadSessionExport(sessionId)
1701
+ if (next?.phase === 'failed') toast(command === 'compact'
1702
+ ? t('ds.compactFailed', { msg: next.message || t('ds.sessionRecoveryFailed') })
1703
+ : t('ds.commandFailed', { command, msg: next.message || t('ds.sessionRecoveryFailed') }), 'err')
1704
+ else toast(command === 'compact' ? t('ds.compactComplete') : t('ds.commandComplete', { command }), 'ok')
1705
+ }
1706
+ }
1707
+ ensureCompactionMonitoring()
1708
+ if (state.current === sessionId) updateComposerStatus()
1709
+ }
1710
+ async function refreshCompactionStatus(sessionId = state.current) {
1711
+ if (!sessionId) return
1712
+ const connection = captureConnection()
1713
+ try {
1714
+ const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(8000) : undefined
1715
+ const url = new URL(connection.server + '/remote/api/command-status', location.href)
1716
+ url.searchParams.set('sessionId', sessionId)
1717
+ const res = await fetch(url, { headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }, ...(signal ? { signal } : {}) })
1718
+ if (!connection.valid()) return
1719
+ if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
1720
+ if (!res.ok) return
1721
+ if (!connection.valid()) return
1722
+ const body = await res.json().catch(() => null)
1723
+ if (!connection.valid()) return
1724
+ const operation = body?.operation || body?.compact
1725
+ if (!operation) return
1726
+ if (operation.startedAt && activeCompaction(sessionId)?.startedAt > Number(operation.startedAt)) return
1727
+ const pending = state.pendingCommands[sessionId]
1728
+ if (operation.active === true) {
1729
+ const terminal = state.compactionTerminals?.[sessionId]
1730
+ if (terminal && Number(operation.startedAt) <= terminal.startedAt) return
1731
+ delete state.pendingCommands[sessionId]
1732
+ setCompactionStatus(sessionId, { ...operation, source: 'status' })
1733
+ } else if (activeCompaction(sessionId) && activeCompaction(sessionId).source !== 'event') {
1734
+ setCompactionStatus(sessionId, operation)
1735
+ } else if (pending) {
1736
+ if (operation.phase === 'failed') toast(t('ds.commandFailed', { command: pending, msg: operation.message || t('ds.sessionRecoveryFailed') }), 'err')
1737
+ delete state.pendingCommands[sessionId]
1738
+ }
1739
+ } catch {}
1740
+ }
1741
+ function ensureCompactionMonitoring() {
1742
+ const active = Object.values(state.compactions).some(compact => compact?.active)
1743
+ if (!active) {
1744
+ if (state.compactionPollTimer) clearInterval(state.compactionPollTimer)
1745
+ if (state.compactionClockTimer) clearInterval(state.compactionClockTimer)
1746
+ state.compactionPollTimer = null
1747
+ state.compactionClockTimer = null
1748
+ return
1749
+ }
1750
+ if (!state.compactionClockTimer) state.compactionClockTimer = setInterval(() => { if (activeCompaction()) updateComposerStatus() }, 1000)
1751
+ if (!state.compactionPollTimer) state.compactionPollTimer = setInterval(() => {
1752
+ const compact = activeCompaction()
1753
+ if (compact && compact.source !== 'event') void refreshCompactionStatus()
1754
+ }, 3000)
1755
+ }
1756
+ function observeCompactionEvent(sessionId, event, meta = {}) {
1757
+ if (!event || !sessionId || !['compaction/start','compaction/end','session/end-seed'].includes(event.type)) return
1758
+ state.compactionSeqs ||= {}; state.compactionBootAt ||= Date.now()
1759
+ const seq = Number(event.seq), previous = activeCompaction(sessionId)
1760
+ if (seq > 0 && seq <= (state.compactionSeqs[sessionId] || 0)) return
1761
+ const id = event.data?.compactionId || ''
1762
+ if (event.type === 'compaction/end' && previous?.compactionId && previous.compactionId !== id) return
1763
+ if (seq > 0) state.compactionSeqs[sessionId] = seq
1764
+ const time = typeof event.time === 'number' ? event.time : Date.parse(event.time)
1765
+ if (event.type === 'compaction/start') {
1766
+ setCompactionStatus(sessionId, { active: true, phase: 'running', compactionId: id,
1767
+ startedAt: previous?.startedAt || (Number.isFinite(time) ? time : Date.now()), source: previous?.source || 'event',
1768
+ notify: meta.replay ? false : previous?.notify || Number.isFinite(time) && time >= state.compactionBootAt })
1769
+ } else {
1770
+ setCompactionStatus(sessionId, { active: false, phase: event.type === 'session/end-seed' ? 'interrupted' : event.data?.error ? 'failed' : 'complete',
1771
+ message: event.data?.error || '', ...(meta.replay || event.type === 'session/end-seed' ? { notify: false } : {}) })
1772
+ }
1773
+ }
1774
+
1775
+ function hydrateSessionProjections(sessionId, projections) {
1776
+ const s = state.byId.get(sessionId)
1777
+ if (!s || !projections || typeof projections !== 'object') return
1778
+ const incomingSeq = Number(projections.asOfSeq) || 0
1779
+ const current = s.projections || { asOfSeq: 0, values: {} }
1780
+ if (projections.kind === 'cached' && current.kind === 'sequenced') return
1781
+ if (current.kind === 'cached' || projections.kind === 'cached') {
1782
+ s.projections = { ...projections, asOfSeq: incomingSeq, kind: projections.kind || 'sequenced', values: { ...(current.values || {}), ...(projections.values || {}) } }
1783
+ return
1784
+ }
1785
+ const currentSeq = Number(current.asOfSeq) || 0
1786
+ if (incomingSeq < currentSeq) return
1787
+ s.projections = {
1788
+ kind: projections.kind || current.kind || 'sequenced',
1789
+ asOfSeq: Math.max(currentSeq, incomingSeq),
1790
+ values: { ...(current.values || {}), ...(projections.values || {}) }
1791
+ }
1792
+ }
1793
+ function applyPendingProjections() {
1794
+ for (const [sessionId, projections] of state.pendingProjections) {
1795
+ if (!state.byId.has(sessionId)) continue
1796
+ hydrateSessionProjections(sessionId, projections)
1797
+ state.pendingProjections.delete(sessionId)
1798
+ }
1799
+ }
1800
+ function applyProjection(sessionId, key, value, seq) {
1801
+ const s = state.byId.get(sessionId)
1802
+ if (!s) {
1803
+ const pending = state.pendingProjections.get(sessionId) || { asOfSeq: 0, values: {} }
1804
+ pending.values[key] = value
1805
+ pending.asOfSeq = Math.max(pending.asOfSeq || 0, seq || 0)
1806
+ state.pendingProjections.set(sessionId, pending)
1807
+ return
1808
+ }
1809
+ if (s.projections?.kind === 'cached') s.projections = { kind: 'sequenced', asOfSeq: 0, values: { ...(s.projections.values || {}) } }
1810
+ const currentSeq = Number(s.projections?.asOfSeq) || 0
1811
+ if (seq && seq < currentSeq) return
1812
+ s.projections = s.projections || { asOfSeq: 0, values: {} }
1813
+ s.projections.values = s.projections.values || {}
1814
+ s.projections.values[key] = value
1815
+ s.projections.asOfSeq = Math.max(currentSeq, seq || 0)
1816
+ if (state.current === sessionId) {
1817
+ renderSessions()
1818
+ window.DshInsights?.update()
1819
+ if (['goal', 'todos'].includes(key)) renderSessionCards()
1820
+ }
1821
+ if (['title', 'goal', 'todos', 'plan', 'sessionListMetadata'].includes(key)) scheduleSessionsRefresh()
1822
+ }
1823
+ function setSessionRecovery(status, error = '') {
1824
+ state.sessionRecovery = { status, error: String(error || '') }
1825
+ updateSessionActions()
1826
+ }
1827
+ function recoveryLabel() {
1828
+ const status = state.sessionRecovery.status
1829
+ if (status === 'loading' || status === 'resuming') return t('ds.sessionRecovering')
1830
+ if (status === 'error') return t('ds.sessionRecoveryFailed')
1831
+ return ''
1832
+ }
1833
+ function resyncCurrentSession() {
1834
+ if (!state.current) return Promise.resolve()
1835
+ return loadHistory().then(() => {
1836
+ if (state.current) { renderSessionCards(); updateComposerStatus(); updateSessionActions() }
1837
+ })
1838
+ }
1839
+ // Coalesce activity/status signals, including signals received during a history read.
1840
+ function scheduleSessionSync(sessionId = state.current, delay = 250) {
1841
+ if (!sessionId || sessionId !== state.current) return
1842
+ const history = state.history, connection = captureConnection()
1843
+ if (history.syncTimer) return
1844
+ delay = Math.max(delay, 2000 - (Date.now() - (history.lastSyncAt || 0)))
1845
+ history.syncTimer = setTimeout(() => {
1846
+ history.syncTimer = null
1847
+ if (!connection.valid() || state.current !== sessionId || state.history !== history) return
1848
+ if (history.loading) { scheduleSessionSync(sessionId, 500); return }
1849
+ void resyncCurrentSession().catch(() => {})
1850
+ }, delay)
1851
+ }
1852
+ function sessionSyncTick() {
1853
+ if (document.visibilityState === 'visible' && state.token && navigator.onLine !== false &&
1854
+ state.current && !state.history.loading && Date.now() - (state.history.lastSyncAt || 0) >= 15000) scheduleSessionSync(state.current, 0)
1855
+ }
1856
+ function rememberRuntimeError(sessionId, message) {
1857
+ if (!sessionId) return
1858
+ state.runtimeErrors ||= new Map()
1859
+ state.runtimeErrors.set(sessionId, String(message || ''))
1860
+ if (state.runtimeErrors.size > 100) state.runtimeErrors.delete(state.runtimeErrors.keys().next().value)
1861
+ if (sessionId === state.current) { renderHistory(); scheduleSessionSync(sessionId) }
1862
+ }
1863
+ function resyncAfterStreamOpen() {
1864
+ if (!state.current || Date.now() - state.lastStreamResyncAt < 1200) return
1865
+ state.lastStreamResyncAt = Date.now()
1866
+ void refreshSessions().then(() => resyncCurrentSession())
1867
+ }
1868
+ function proj(s, key, d) { return s?.projections?.values?.[key] ?? d }
1869
+ function optionalPluginConfig(connection = captureConnection()) {
1870
+ return { connection, valid: connection.valid, url: path => connection.server + path,
1871
+ headers: { authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() } }
1872
+ }
1873
+ function availableInsightTabs(capabilities) {
1874
+ return [...(capabilities.context ? ['context'] : []), ...(capabilities.cost ? ['cost'] : [])]
1875
+ }
1876
+ async function refreshInsightEntry() {
1877
+ const control = $('btn-insights'), id = state.current, connection = captureConnection()
1878
+ if (!control || !id || !connection.token || !window.DshExtensions) { control?.classList.add('hidden'); return }
1879
+ const capabilities = await window.DshExtensions.getCapabilities(optionalPluginConfig(connection))
1880
+ if (!connection.valid() || state.current !== id) return
1881
+ const tabs = availableInsightTabs(capabilities)
1882
+ control.classList.toggle('hidden', !tabs.length)
1883
+ const label = t(tabs.length === 2 ? 'ds.insights' : tabs[0] === 'cost' ? 'ds.insightsCost' : 'ds.insightsContext')
1884
+ control.textContent = label; control.title = label; control.setAttribute('aria-label', label)
1885
+ }
1886
+ async function openInsights(tab = 'context', fullPage = false) {
1887
+ const connection = captureConnection(), id = state.current
1888
+ const capabilities = await window.DshExtensions.getCapabilities(optionalPluginConfig(connection))
1889
+ if (!connection.valid() || state.current !== id || !id) return
1890
+ const allowedTabs = availableInsightTabs(capabilities)
1891
+ if (!allowedTabs.length) { void refreshInsightEntry(); return }
1892
+ window.DshInsights?.close()
1893
+ const view = fullPage ? conversationView : null, wasPaused = view?.paused
1894
+ view?.pause()
1895
+ window.DshInsights?.open({ tab, fullPage, allowedTabs, connection, url: path => connection.server + path,
1896
+ getSession: () => state.byId.get(state.current), getTitle: () => titleOf(state.byId.get(state.current)),
1897
+ onFullPage: selected => void openInsights(selected, true),
1898
+ onClose: () => { if (view && !wasPaused && connection.valid() && state.current === id && state.view === 'view-chat') view.resume() } })
1899
+ }
1900
+ function sessionTitleValue(s) {
1901
+ const value = proj(s, 'title', '')
1902
+ return value == null ? '' : String(value).trim()
1903
+ }
1904
+ function hasSessionTitle(s) { return !!sessionTitleValue(s) }
1905
+ function titleOf(s) { return sessionTitleValue(s) || (s?.sessionId ? t('ds.sessionUntitled') : t('ds.sessions')) }
1906
+ function sessionLabelOf(s) {
1907
+ const title = titleOf(s)
1908
+ if (!s?.sessionId || hasSessionTitle(s)) return title
1909
+ return `${title} · ${String(s.sessionId).slice(-8)}`
1910
+ }
1911
+ function isTopLevelSession(session) {
1912
+ // Ordinary forks also carry parentSessionId; only explicit subagents leave the main list.
1913
+ return !!session && session.origin !== 'subagent'
1914
+ }
1915
+ // DSH marks sessions created via "new session" but never prompted as blank and hides
1916
+ // them in its own UI; keep the same semantics here so they do not occupy the list,
1917
+ // the workspace tree or the home stats.
1918
+ function isVisibleSession(session) { return isTopLevelSession(session) && !session?.blank }
1919
+ function topLevelSessions() { return state.sessions.filter(isVisibleSession) }
1920
+ const GOAL_TERMINAL_PHASES = new Set(['complete', 'cleared'])
1921
+ function isGoalTerminal(goal) {
1922
+ return !!goal && GOAL_TERMINAL_PHASES.has(goal.phase)
1923
+ }
1924
+ function goalOf(s) {
1925
+ const p = proj(s, 'goal')
1926
+ if (!p) return null
1927
+ return p.goal && typeof p.goal === 'object' ? p.goal : p
1928
+ }
1929
+ const COLLAPSED_GOALS_KEY = 'dshCollapsedGoalsV1'
1930
+ function collapsedGoals() {
1931
+ try {
1932
+ const value = JSON.parse(LS.get(COLLAPSED_GOALS_KEY, '[]'))
1933
+ return Array.isArray(value) ? value.filter(item => item && typeof item.sessionId === 'string' && typeof item.goalId === 'string') : []
1934
+ } catch { return [] }
1935
+ }
1936
+ function goalDisplayId(goal) { return String(goal?.id || '__current__') }
1937
+ function isGoalCollapsed(sessionId, goal) {
1938
+ const goalId = goalDisplayId(goal)
1939
+ return collapsedGoals().some(item => item.sessionId === sessionId && item.goalId === goalId)
1940
+ }
1941
+ function setGoalCollapsed(sessionId, goal, collapsed) {
1942
+ const goalId = goalDisplayId(goal)
1943
+ const next = collapsedGoals().filter(item => item.sessionId !== sessionId)
1944
+ if (collapsed) next.push({ sessionId, goalId })
1945
+ LS.set(COLLAPSED_GOALS_KEY, JSON.stringify(next.slice(-100)))
1946
+ }
1947
+ function onSessionEvent(sessionId, event, meta = {}) {
1948
+ if (collectApprovalEvent(sessionId, event)) renderApprovalRecordsDesktop()
1949
+ observeCompactionEvent(sessionId, event, meta)
1950
+ const failedSession = state.byId.get(sessionId)
1951
+ if (event?.type === 'turn/end' && event.data?.reason?.kind === 'error' && failedSession) {
1952
+ failedSession.error = true; failedSession.running = false
1953
+ if (state.current === sessionId) { renderQueue(); updateComposerStatus() }
1954
+ }
1955
+ if (event?.type === 'turn/start' || event?.type === 'turn/end') {
1956
+ noteSessionTurnTime(sessionId, event)
1957
+ renderSessions()
1958
+ if (event.type === 'turn/start') state.runtimeErrors?.delete(sessionId)
1959
+ if (event.type === 'turn/end' && !meta.replay) scheduleSessionSync(sessionId)
1960
+ }
1961
+ const session = state.byId.get(sessionId)
1962
+ if((event?.type==='session/title'||event?.type==='title')&&event.data?.title&&session){session.projections??={values:{}};session.projections.values??={};session.projections.values.title=event.data.title;if(state.current===sessionId)updateSessionActions()}
1963
+ if (event?.type === 'agent/status' && session) {
1964
+ if (event.data?.running) state.runtimeErrors?.delete(sessionId)
1965
+ else if (!meta.replay) scheduleSessionSync(sessionId)
1966
+ session.running = !!event.data?.running
1967
+ if (state.current === sessionId) { renderQueue(); updateComposerStatus() }
1968
+ }
1969
+ if (state.current === sessionId && event) {
1970
+ const h = state.history
1971
+ const reasoningChanged = applyReasoningStreamEvent(event)
1972
+ if (event.type === 'assistant/chunk' || event.type === 'reasoning-chunks') {
1973
+ if (reasoningChanged) scheduleReasoningRender()
1974
+ return
1975
+ }
1976
+ const seq = event.seq
1977
+ if (seq != null && !h.seqs.has(seq) && shouldShowEvent(event.type, event)) {
1978
+ h.seqs.add(seq)
1979
+ window.DshHistory.insertSorted(h.visible, { seq, event })
1980
+ trimVisible()
1981
+ renderHistory()
1982
+ scheduleHistoryCacheSave()
1983
+ }
1984
+ if (String(event.type || '').startsWith('goal/') || String(event.type || '').startsWith('todo/')) renderSessionCards()
1985
+ }
1986
+ }
1987
+
1988
+ /* ---------------- 会话 ---------------- */
1989
+ function scheduleSessionsRefresh() {
1990
+ if (state.refreshTimer) return
1991
+ const connection = captureConnection()
1992
+ state.refreshTimer = setTimeout(() => { state.refreshTimer = null; if (connection.valid()) void refreshSessions() }, 150)
1993
+ }
1994
+ async function refreshSessions() {
1995
+ if(typeof restoreCachedSessionList==='function')restoreCachedSessionList()
1996
+ const connection = captureConnection(), request = ++sessionsRequest
1997
+ const v = await safeRpc('session.list', {}, '')
1998
+ if (!connection.valid() || request !== sessionsRequest) return
1999
+ if (!v) { renderSessions(); renderOverviewDesktop(); return }
2000
+ state.sessions = v.items || []
2001
+ state.byId = new Map(state.sessions.map(s => [s.sessionId, s]))
2002
+ for (const [id, child] of Object.entries(state.subagentSessions || {})) {
2003
+ const listed = state.byId.get(id)
2004
+ const merged = listed ? { ...child, ...listed, parentSessionId: child.parentSessionId, subagentMode: child.subagentMode, origin: 'subagent' } : child
2005
+ state.byId.set(id, merged)
2006
+ state.subagentSessions[id] = merged
2007
+ }
2008
+ applyPendingProjections()
2009
+ try{LS.set(historyCacheScope()+':sessions',JSON.stringify(state.sessions.slice(0,80)))}catch{}
2010
+ if(typeof window!=='undefined')window.DshDoctorEntry?.consumeSessionLink(openSession,state.byId)
2011
+ renderSessions()
2012
+ scheduleWorkbenchRefresh()
2013
+ renderOverviewDesktop()
2014
+ }
2015
+ function sessionCwd(s) { return typeof s?.cwd === 'string' ? s.cwd.trim() : '' }
2016
+ function sessionWorkspaceLabel(s) {
2017
+ const cwd = sessionCwd(s)
2018
+ return cwd || t('ds.workspaceUnknown')
2019
+ }
2020
+ function sessionSortTime(s) {
2021
+ return Math.max(Number(state.sessionTurnTimes[s?.sessionId]) || 0, Number(s?.updatedAt) || 0, Number(s?.createdAt) || 0)
2022
+ }
2023
+ function sessionWorkspaceOrderKey(s) {
2024
+ return 'path:' + (sessionWorkspaceLabel(s) || 'workspace-unknown')
2025
+ }
2026
+ function commitWorkspaceGroupOrder(order) {
2027
+ saveWorkbenchOrder(value => { value.workspaceIds = order.map(String) })
2028
+ renderSessions()
2029
+ toast(t('ds.wbOrderSaved'), 'ok')
2030
+ }
2031
+ function noteSessionTurnTime(sessionId, eventOrTime) {
2032
+ const raw = typeof eventOrTime === 'object' ? eventOrTime?.time : eventOrTime
2033
+ const time = Number(raw) > 0 ? Number(raw) : Date.now()
2034
+ if (!sessionId || !Number.isFinite(time)) return
2035
+ state.sessionTurnTimes[sessionId] = Math.max(Number(state.sessionTurnTimes[sessionId]) || 0, time)
2036
+ }
2037
+ function workspaceDisplayName(label) {
2038
+ const value = String(label || '').trim()
2039
+ if (!value || value === t('ds.workspaceUnknown')) return value || t('ds.workspaceUnknown')
2040
+ const clean = value.replace(/[\\/]+$/, '')
2041
+ const parts = clean.split(/[\\/]/).filter(Boolean)
2042
+ return parts[parts.length - 1] || value
2043
+ }
2044
+ function sortedSessions() {
2045
+ const items = topLevelSessions()
2046
+ if (state.sessionSort === 'workspace') {
2047
+ return items.sort((a, b) => {
2048
+ const aw = sessionCwd(a) || '\uffff'
2049
+ const bw = sessionCwd(b) || '\uffff'
2050
+ const byWorkspace = aw.localeCompare(bw, undefined, { numeric: true, sensitivity: 'base' })
2051
+ return byWorkspace || (sessionSortTime(b) - sessionSortTime(a))
2052
+ })
2053
+ }
2054
+ return items.sort((a, b) => sessionSortTime(b) - sessionSortTime(a))
2055
+ }
2056
+ function renderSessions() {
2057
+ const allItems = sortedSessions()
2058
+ const wbIds = new Set()
2059
+ if (state.wb.bound && state.wb.projects) for (const w of state.wb.projects) for (const id of (w.sessionIds || [])) wbIds.add(id)
2060
+ const root = state.wb.bound ? state.wb.path : ''
2061
+ const archivedSet = new Set(state.archivedIds || [])
2062
+ const visible = allItems.filter(s => {
2063
+ if (!state.wb.bound) return true
2064
+ if (archivedSet.has(s.sessionId)) return true
2065
+ return !(wbIds.has(s.sessionId) || wbStrictInside(s.cwd, root))
2066
+ })
2067
+ const archived = visible.filter(s => archivedSet.has(s.sessionId))
2068
+ const main = visible.filter(s => !archivedSet.has(s.sessionId))
2069
+ const showArchived = LS.get('dsShowArchivedV1', '0') === '1'
2070
+ const renderSession = s => {
2071
+ const workspace = sessionWorkspaceLabel(s)
2072
+ const workspaceName = workspaceDisplayName(workspace)
2073
+ const title = sessionLabelOf(s)
2074
+ return `<button class="ds-session-item ${state.current === s.sessionId ? 'current' : ''}" data-id="${esc(s.sessionId)}">
2075
+ <span class="ds-session-title">${esc(title)}</span>
2076
+ <span class="ds-session-workspace" title="${esc(workspace)}">⌂ ${esc(workspaceName)}</span>
2077
+ <span class="ds-session-meta"><span class="ds-session-dot ${s.running ? 'running' : ''}"></span>${fmtTime(sessionSortTime(s))}</span>
2078
+ </button>`
2079
+ }
2080
+ const renderItems = (items) => {
2081
+ if (state.sessionSort !== 'workspace') return items.map(renderSession).join('')
2082
+ const groups = []
2083
+ const byKey = new Map()
2084
+ for (const session of items) {
2085
+ const key = sessionWorkspaceOrderKey(session)
2086
+ let group = byKey.get(key)
2087
+ if (!group) {
2088
+ group = { key, label: workspaceDisplayName(sessionWorkspaceLabel(session)), path: sessionWorkspaceLabel(session), items: [] }
2089
+ byKey.set(key, group)
2090
+ groups.push(group)
2091
+ }
2092
+ group.items.push(session)
2093
+ }
2094
+ const { value } = workbenchOrderScopeValue()
2095
+ return orderedItems(groups, value.workspaceIds, group => group.key).map(group => `<div class="ds-session-workspace-group" data-workspace-group="${esc(group.key)}" data-motion-key="${esc(group.key)}">
2096
+ <div class="ds-session-group" data-reorder-handle title="${esc(group.path)}"><span class="ds-session-group-drag-handle" aria-hidden="true">⠿</span><span class="ds-session-group-icon" aria-hidden="true">⌂</span><span class="ds-session-group-name">${esc(group.label)}</span></div>
2097
+ ${orderedWorkspaceSessions(group.key, group.items).map(renderSession).join('')}
2098
+ </div>`).join('')
2099
+ }
2100
+ const divider = archived.length ? `<button class="ds-archived-toggle" type="button" data-archived-toggle>${esc(showArchived ? t('wb.archivedShown') : t('wb.archivedHidden'))}</button>` : ''
2101
+ const hiddenByWorkbench = allItems.length - visible.length
2102
+ const html = renderItems(main) + divider + (showArchived ? renderItems(archived) : '') || `<div class="ds-empty">${esc(hiddenByWorkbench ? t('wb.flatHidden', { n: hiddenByWorkbench }) : t('ds.sessionsEmpty'))}</div>`
2103
+ $('session-list').innerHTML = html
2104
+ $('mobile-session-list').innerHTML = html
2105
+ window.DshMotion?.list($('session-list'), '.ds-session-item')
2106
+ window.DshMotion?.list($('mobile-session-list'), '.ds-session-item')
2107
+ for (const list of [$('session-list'), $('mobile-session-list')].filter(Boolean)) {
2108
+ window.DshMotion?.bindLongPressReorder(list, '.ds-session-workspace-group', {
2109
+ handleSelector: '.ds-session-group',
2110
+ onCommit: ({ order }) => commitWorkspaceGroupOrder(order)
2111
+ })
2112
+ window.DshMotion?.bindLongPressReorder(list, '.ds-session-item', {
2113
+ groupSelector: '.ds-session-workspace-group',
2114
+ handleSelector: '.ds-session-item',
2115
+ onCommit: ({ item, order }) => commitWorkspaceSessionOrder(item.closest('[data-workspace-group]')?.dataset.workspaceGroup, order)
2116
+ })
2117
+ }
2118
+ $('session-list').classList.toggle('workspace-sorted', state.sessionSort === 'workspace')
2119
+ $('mobile-session-list').classList.toggle('workspace-sorted', state.sessionSort === 'workspace')
2120
+ const sort = $('session-sort')
2121
+ if (sort) sort.value = state.sessionSort
2122
+ document.querySelectorAll('[data-archived-toggle]').forEach(b => b.addEventListener('click', () => {
2123
+ LS.set('dsShowArchivedV1', LS.get('dsShowArchivedV1', '0') === '1' ? '0' : '1')
2124
+ renderSessions()
2125
+ }))
2126
+ document.querySelectorAll('[data-id]').forEach(b => b.addEventListener('click', () => openSession(b.dataset.id)))
2127
+ renderWorkbench()
2128
+ }
2129
+
2130
+ const emptySessionCleanup = new Set()
2131
+ async function archiveEmptySessionOnLeave(sessionId, leaving = false) {
2132
+ const base = state.server, connection=captureConnection()
2133
+ const protectedSession = () => !connection.valid() || state.server !== base || (!leaving && state.current !== sessionId)
2134
+ || !!state.byId.get(sessionId)?.parentSessionId || state.byId.get(sessionId)?.origin === 'subagent'
2135
+ || !state.byId.has(sessionId) || state.byId.get(sessionId)?.running
2136
+ || state.sessionActivity?.has(sessionId) || state.pendingPrompts?.has(sessionId)
2137
+ || (state.queues[sessionId] || []).length > 0
2138
+ || (state.composerImages || []).length > 0 || !!$('composer')?.value?.trim()
2139
+ if (!sessionId || emptySessionCleanup.has(sessionId) || protectedSession()) return false
2140
+ emptySessionCleanup.add(sessionId)
2141
+ try {
2142
+ const history = await rpc('session.history', { sessionId, maxMessages: 1 })
2143
+ if (protectedSession() || !Array.isArray(history?.events) || history.events.some(item => !['permission/preset', 'sandbox/mode', 'approval/policy'].includes(item?.event?.type || item?.type))
2144
+ || history.hasMore || (history.partialReasoning || []).length) return false
2145
+ const result = await rpc('workspace.archiveSession', { sessionId })
2146
+ if (!Array.isArray(result?.archivedSessionIds) || !result.archivedSessionIds.includes(sessionId)) return false
2147
+ if (state.server !== base) return false
2148
+ await refreshSessions()
2149
+ return true
2150
+ } catch { return false } // 离线、历史未知或归档失败时保留会话。
2151
+ finally { emptySessionCleanup.delete(sessionId) }
2152
+ }
2153
+
2154
+ async function openSession(id) {
2155
+ globalThis.DshDiagnostics?.record('session.open',{phase:'start',sessionId:id,server:state.server})
2156
+ if (state.current && state.current !== id) void archiveEmptySessionOnLeave(state.current,true)
2157
+ cancelHistoryLoad()
2158
+ state.current = id
2159
+ setSessionRecovery('loading')
2160
+ state.history = emptyDesktopHistory()
2161
+ const openingHistory=state.history, openingConnection=captureConnection()
2162
+ state.models = { loaded: false, loading: false, groups: [], current: null, failures: [] }
2163
+ showView('view-chat')
2164
+ $('ds-title').textContent = titleOf(state.byId.get(id)) || t('ds.sessions')
2165
+ updateSessionActions()
2166
+ getConversationView().reset()
2167
+ $('history').innerHTML = `<div class="ds-empty">${t('ds.historyLoading')}</div>`
2168
+ renderSessions()
2169
+ renderSessionCards()
2170
+ renderQueue()
2171
+ renderSessionPendingDesktop()
2172
+ updateComposerStatus()
2173
+ void refreshCompactionStatus(id)
2174
+ try { const restored=await restoreCachedHistory();globalThis.DshDiagnostics?.record('history.cache',{phase:restored?'hit':'miss',sessionId:id}) } catch(error) {
2175
+ globalThis.DshDiagnostics?.record('history.cache',{phase:'failed',sessionId:id,...globalThis.DshDiagnostics.errorFacts(error)})
2176
+ if(state.current!==id||state.history!==openingHistory||!openingConnection.valid())return
2177
+ // A broken local cache must not prevent fetching the authoritative history.
2178
+ cancelHistoryLoad()
2179
+ Object.assign(openingHistory,emptyDesktopHistory())
2180
+ getConversationView().reset()
2181
+ }
2182
+ if(state.current!==id||state.history!==openingHistory||!openingConnection.valid())return
2183
+ await loadHistory()
2184
+ }
2185
+ async function closeSession() {
2186
+ globalThis.DshDiagnostics?.record('session.back',{phase:'start',sessionId:state.current,loading:state.history.loading,loaded:state.history.loaded,renderErrors:state.history.renderError?1:0})
2187
+ const sessionId = state.current
2188
+ const closing = state.byId.get(sessionId)
2189
+ // Ordinary forks also carry parentSessionId; only a subagent record returns to its parent.
2190
+ const parentId = closing?.origin === 'subagent' ? closing.parentSessionId : null
2191
+ if (parentId && parentId !== sessionId) return openSession(parentId)
2192
+ const wasLoading = state.history.loading
2193
+ cancelHistoryLoad()
2194
+ const cleanup=sessionId&&!wasLoading&&state.history.loaded&&!state.history.loading&&!state.history.renderError
2195
+ state.current = null
2196
+ setSessionRecovery('idle')
2197
+ state.history = emptyDesktopHistory()
2198
+ showView('view-sessions')
2199
+ globalThis.DshDiagnostics?.record('session.back',{phase:'navigate',sessionId})
2200
+ const cards = $('session-cards')
2201
+ if (cards) cards.innerHTML = ''
2202
+ renderQueue()
2203
+ renderSessionPendingDesktop()
2204
+ updateComposerStatus()
2205
+ updateSessionActions()
2206
+ if(cleanup)await archiveEmptySessionOnLeave(sessionId,true)
2207
+ }
2208
+
2209
+ function restoreCachedSessionList() {
2210
+ if(state.sessions.length)return
2211
+ try{const items=JSON.parse(LS.get(historyCacheScope()+':sessions',''));if(!Array.isArray(items))return;state.sessions=items.filter(item=>typeof item?.sessionId==='string').slice(0,80);state.byId=new Map(state.sessions.map(item=>[item.sessionId,item]));renderSessions()}catch{}
2212
+ }
2213
+
2214
+ let conversationView = null
2215
+ function historyCacheScope(server=state.server,token=state.token) { const hash=new SHA256();hash.update(new TextEncoder().encode(JSON.stringify([server||location.origin,token])));return 'historyCacheV2:'+hash.hex() }
2216
+ function captureChatImage() {
2217
+ const connection=captureConnection(),sessionId=state.current
2218
+ return {scope:historyCacheScope(),valid:()=>connection.valid()&&state.current===sessionId}
2219
+ }
2220
+ function historySource(value) {
2221
+ state.history.source=value
2222
+ const el=$('history-source')
2223
+ if(el)el.textContent=t(({cache:'ds.historyCached',syncing:'ds.historySyncing',synced:'ds.historySynced',saved:'ds.historySaved',offline:'ds.historyOffline',saveFailed:'ds.historyCacheFailed',error:'ds.historyRenderFailed'})[value]||'ds.historySynced')
2224
+ }
2225
+ function getConversationView() {
2226
+ if(!conversationView)conversationView=new window.DshHistory.HistoryView($('history'),{
2227
+ html:entry=>eventHtml(entry),
2228
+ errorLabel:()=>t('ds.historyRenderFailed'),
2229
+ older:()=>loadHistory(false),olderLabel:()=>t('ds.historyEarlier'),loadingLabel:()=>t('ds.historyLoadingEarlier'),live:partialReasoningHtml,
2230
+ retry:()=>loadHistory(true),retryLabel:()=>t('ds.historyRetry'),unreadableLabel:()=>I18N.lang==='en'?'No displayable messages on this page. Load earlier records or retry. If DSH reports a migration failure, open the original session in DSH.':'本页历史没有可显示的消息,请加载更早记录或重试。如提示格式迁移失败,请先在 DSH 中打开原会话。',
2231
+ changed:view=>{state.history.renderStart=view.start;state.history.renderEnd=view.end;const latest=$('btn-history-latest');if(latest){latest.classList.toggle('hidden',view.atBottom&&view.unread===0&&!state.history.tailEvicted);latest.textContent=t('ds.historyLatest')+(view.unread?' ('+view.unread+')':view.hasPending?' · '+(I18N.lang==='en'?'New content':'有新内容'):'')}},
2232
+ scrolled:()=>{}
2233
+ })
2234
+ return conversationView
2235
+ }
2236
+ function scheduleHistoryCacheSave() {
2237
+ clearTimeout(scheduleHistoryCacheSave._t)
2238
+ const connection=captureConnection(),id=state.current,history=state.history,scope=historyCacheScope()
2239
+ scheduleHistoryCacheSave._t=setTimeout(()=>{if(connection.valid()&&state.current===id&&state.history===history)void saveHistoryCache(scope,id,history)},500)
2240
+ }
2241
+ async function saveHistoryCache(scope=historyCacheScope(),id=state.current,history=state.history) {
2242
+ if(!id||!history.visible.length||history.tailEvicted)return
2243
+ const saved=await window.DshHistory.cacheSave(scope,id,{title:titleOf(state.byId.get(id)),events:history.visible.slice(-250),minSeq:history.visible.slice(-250)[0]?.seq??history.minSeq,hasMore:history.hasMore||history.visible.length>250,partialReasoning:[...history.partialReasoning.values()]})
2244
+ if(!saved&&state.current===id&&state.history===history&&scope===historyCacheScope())historySource('saveFailed')
2245
+ if(saved&&state.current===id&&state.history===history&&scope===historyCacheScope()&&['synced','saveFailed'].includes(history.source))historySource('saved')
2246
+ }
2247
+ async function restoreCachedHistory() {
2248
+ const connection=captureConnection(),id=state.current,history=state.history,scope=historyCacheScope()
2249
+ if(!id)return false
2250
+ const cached=await window.DshHistory.cacheLoad(scope,id,legacyId=>window.DshHistory.decodeLegacy(LS.get(scope,''),legacyId))
2251
+ if(!connection.valid()||state.current!==id||state.history!==history||(history.loaded&&!history.cached)||!cached?.events?.length)return false
2252
+ history.visible=cached.events.slice(-250).filter(entry=>entry?.seq!=null&&shouldShowEvent(entry.event?.type,entry.event)).sort((a,b)=>a.seq-b.seq)
2253
+ history.seqs=new Set(history.visible.map(entry=>entry.seq));history.loaded=true;history.cached=true;history.hasMore=cached.events.length>250||cached.hasMore!==false;history.minSeq=cached.events.length>250?(history.visible[0]?.seq??Infinity):Number.isFinite(cached.minSeq)?cached.minSeq:history.visible[0]?.seq??Infinity
2254
+ if(cached.title&&!hasSessionTitle(state.byId.get(id)))hydrateSessionProjections(id,{values:{title:cached.title},asOfSeq:0})
2255
+ applyReasoningBaseline(cached.partialReasoning||[]);historySource('cache');setSessionRecovery('cached');renderHistory(true)
2256
+ return true
2257
+ }
2258
+ function trimVisible(direction='tail') {
2259
+ const h=state.history,excess=h.visible.length-5000
2260
+ if(excess<=0)return
2261
+ const older=direction==='older'||conversationView?.reading
2262
+ const removed=older?h.visible.splice(5000):h.visible.splice(0,excess)
2263
+ for(const entry of removed)h.seqs.delete(entry.seq)
2264
+ if(older)h.tailEvicted=true
2265
+ else{h.minSeq=h.visible[0]?.seq??Infinity;h.headEvicted=true;h.hasMore=true}
2266
+ }
2267
+
2268
+ function cancelHistoryLoad() {
2269
+ const history=state.history
2270
+ if(!history)return
2271
+ const controller=history.loadController
2272
+ history.loadController=null
2273
+ history.loading=false
2274
+ controller?.abort()
2275
+ clearTimeout(history.syncTimer);history.syncTimer=null
2276
+ }
2277
+ function recoverSessionHistory() {
2278
+ cancelHistoryLoad()
2279
+ scheduleSessionSync()
2280
+ }
2281
+ async function loadHistory(reset = true) {
2282
+ const connection=captureConnection(),id=state.current,history=state.history
2283
+ if(!id||history.loading||(!reset&&Date.now()<(history.retryAfter||0)))return
2284
+ const diagnostic=globalThis.DshDiagnostics?.start('history.load',{sessionId:id,server:state.server,reset,cached:!!history.cached,count:history.visible.length})
2285
+ const reasoningVersion=history.reasoningVersion||0,hadContent=history.visible.length>0
2286
+ const controller=new AbortController()
2287
+ history.loadController=controller
2288
+ const valid=()=>connection.valid()&&state.current===id&&state.history===history&&history.loadController===controller
2289
+ history.loading=true
2290
+ history.lastSyncAt=Date.now()
2291
+ let v
2292
+ // Contain preparation and final DOM failures as well as network errors. Reset
2293
+ // the view before replacing its DOM so an identical retry cannot reuse stale nodes.
2294
+ const failLoad = (error,renderFailure=false) => {
2295
+ diagnostic?.fail(error)
2296
+ history.loading=false;history.retryAfter=Date.now()+1500
2297
+ if(error.message==='AUTH'){return}
2298
+ if(history.visible.length&&!renderFailure){try{renderHistory(false,'fixed');history.renderError=!!getConversationView().renderErrors;historySource(history.renderError?'error':'offline');setSessionRecovery(history.renderError?'error':'cached',error.message);return}catch{}}
2299
+ history.renderError=true;historySource('error')
2300
+ setSessionRecovery('error',error.message)
2301
+ getConversationView().reset?.()
2302
+ $('history').innerHTML='<div class="history-empty">'+esc(error.message)+'</div>'
2303
+ const retry=document.createElement('button');retry.type='button';retry.className='history-page-control';retry.textContent=t('ds.historyRetry');retry.addEventListener('click',()=>{void loadHistory(true)});$('history').append(retry)
2304
+ }
2305
+ try {
2306
+ if(reset){if(hadContent)historySource('syncing');else setSessionRecovery('loading')}
2307
+ const network=window.DshNetwork?.profile() || {historyPageSize:60,readTimeout:45000}
2308
+ const payload={sessionId:id,maxMessages:network.historyPageSize}
2309
+ const child=state.subagentSessions?.[id] || state.byId.get(id)
2310
+ if(child?.origin==='subagent' && child.parentSessionId) Object.assign(payload,{parentSessionId:child.parentSessionId,subagentMode:child.subagentMode || 'unknown'})
2311
+ if(!reset&&Number.isFinite(history.minSeq))payload.beforeSeq=history.minSeq
2312
+ getConversationView().more.disabled=true
2313
+ getConversationView().more.textContent=getConversationView().options.loadingLabel()
2314
+ v=await window.DshNetwork.readWithDeadline(signal=>rpc('session.history',payload,network.readTimeout,signal),network.readTimeout,controller.signal);globalThis.DshDiagnostics?.record('history.load',{phase:'response',traceId:diagnostic?.traceId,sessionId:id,rawCount:Array.isArray(v?.events)?v.events.length:0})
2315
+ if(!valid())return
2316
+ let liveReasoning, rawSeqs, floor
2317
+ liveReasoning=(history.reasoningVersion||0)!==reasoningVersion?new Map(history.partialReasoning):null
2318
+ hydrateSessionProjections(id,v.projections);history.loaded=true
2319
+ const incoming=v.events||[],prepared=[]
2320
+ let approvalChanged=false
2321
+ for (const entry of incoming) {
2322
+ const ev=entry?.event
2323
+ applyReasoningStreamEvent(ev)
2324
+ if(ev?.type==='turn/start'||ev?.type==='turn/end')noteSessionTurnTime(id,ev)
2325
+ if(collectApprovalEvent(id,ev))approvalChanged=true
2326
+ if(ev?.seq==null||!shouldShowEvent(ev.type,ev))continue
2327
+ prepared.push({seq:ev.seq,event:ev,view:entry.view})
2328
+ }
2329
+ rawSeqs=incoming.map(entry=>entry?.event?.seq).filter(Number.isFinite);floor=rawSeqs.length?Math.min(...rawSeqs):Infinity
2330
+ if(reset){const retainedOlder=!!v.hasMore&&history.visible.some(entry=>entry.seq<floor);const ceiling=rawSeqs.length?Math.max(...rawSeqs)+1:Infinity;history.visible=rawSeqs.length?window.DshHistory.reconcile(history.visible,prepared,floor,!!v.hasMore,ceiling):[];history.minSeq=retainedOlder?Math.min(history.minSeq,floor):floor;history.tailEvicted=false}
2331
+ else{history.visible=window.DshHistory.reconcile(history.visible,prepared,floor,true,payload.beforeSeq);history.minSeq=Math.min(history.minSeq,floor)}
2332
+ history.seqs=new Set(history.visible.map(entry=>entry.seq));history.headEvicted=false;trimVisible(reset?'tail':'older')
2333
+ if(liveReasoning)history.partialReasoning=liveReasoning;else applyReasoningBaseline(v.partialReasoning)
2334
+ history.hasMore=(!!v.hasMore||(reset&&history.headEvicted)) && rawSeqs.length>0 && (reset || floor<payload.beforeSeq)
2335
+ try {
2336
+ history.loading=false;history.cached=false
2337
+ updateSessionActions();renderSessionCards()
2338
+ globalThis.DshDiagnostics?.record('history.render',{phase:'start',traceId:diagnostic?.traceId,sessionId:id,count:history.visible.length})
2339
+ renderHistory(!hadContent,reset?'fixed':'keep')
2340
+ history.renderError=!!getConversationView().renderErrors
2341
+ historySource(history.renderError?'error':'synced');setSessionRecovery(history.renderError?'error':'ready')
2342
+ if(approvalChanged)renderApprovalRecordsDesktop()
2343
+ diagnostic?.end({phase:history.renderError?'failed':'rendered',count:history.visible.length,renderedCount:getConversationView().end-getConversationView().start,renderErrors:getConversationView().renderErrors||0})
2344
+ if(!history.renderError)scheduleHistoryCacheSave()
2345
+ } catch(error) { failLoad(error,true) }
2346
+ } catch(error) { if(valid())failLoad(error) }
2347
+ finally { if(history.loadController===controller){history.loading=false;history.loadController=null} }
2348
+ }
2349
+
2350
+
2351
+ const INTERESTING_EVENTS = new Set([
2352
+ 'turn/start', 'turn/end',
2353
+ 'user/message', 'assistant/message', 'assistant/attempt', 'tool/call', 'tool/result',
2354
+ 'agent/status', 'checkpoint/created', 'compaction/complete', 'compaction/summary',
2355
+ 'goal/created', 'goal/updated', 'goal/completed', 'goal/cleared',
2356
+ 'todo/updated', 'plan/updated', 'question/asked', 'question/resolved',
2357
+ 'approval/asked', 'approval/resolved'
2358
+ ])
2359
+ function messageSource(data) {
2360
+ const source = data?.source ?? data?.message?.source
2361
+ return source && typeof source === 'object' ? source : null
2362
+ }
2363
+ function isHumanUserMessage(event) {
2364
+ if (event?.type !== 'user/message') return false
2365
+ const source = messageSource(event.data || {})
2366
+ // Older DSH events may not carry source metadata; keep those visible for compatibility.
2367
+ return !source || source.kind === 'user'
2368
+ }
2369
+ function shouldShowEvent(type, event) {
2370
+ if (!INTERESTING_EVENTS.has(type)) return false
2371
+ if (type === 'user/message' && !isHumanUserMessage(event)) {
2372
+ const data = event?.data || {}
2373
+ const blocks = data.message?.content || data.content || []
2374
+ return systemReminderText(blocks).length > 0
2375
+ }
2376
+ return true
2377
+ }
2378
+ function reasoningStreamKey(data, index) { return `${data?.turn ?? '?'}:${data?.step ?? '?'}:${index ?? '?'}` }
2379
+ function applyReasoningBaseline(items) {
2380
+ if (!Array.isArray(items)) return
2381
+ state.history.reasoningVersion = (state.history.reasoningVersion || 0) + 1
2382
+ state.history.partialReasoning.clear()
2383
+ for (const item of items) state.history.partialReasoning.set(reasoningStreamKey(item, item.index), item)
2384
+ }
2385
+ function applyReasoningStreamEvent(event) {
2386
+ const h = state.history
2387
+ const data = event?.data || {}
2388
+ let changed = false
2389
+ if (event?.type === 'assistant/chunk') {
2390
+ const chunk = data.chunk || {}
2391
+ const key = reasoningStreamKey(data, chunk.index)
2392
+ if (chunk.type === 'block-start' && chunk.blockType === 'reasoning') {
2393
+ h.partialReasoning.set(key, { turn: data.turn, step: data.step, index: chunk.index, text: '' })
2394
+ changed = true
2395
+ } else if (chunk.type === 'reasoning-delta') {
2396
+ const item = h.partialReasoning.get(key) || { turn: data.turn, step: data.step, index: chunk.index, text: '' }
2397
+ item.text += String(chunk.text || '')
2398
+ h.partialReasoning.set(key, item)
2399
+ changed = true
2400
+ } else if (chunk.type === 'block-end' && chunk.block?.type === 'reasoning') {
2401
+ h.partialReasoning.set(key, { turn: data.turn, step: data.step, index: chunk.index, text: String(chunk.block.text ?? chunk.block.content ?? '') })
2402
+ changed = true
2403
+ }
2404
+ } else if (event?.type === 'reasoning-chunks') {
2405
+ const key = reasoningStreamKey(data, data.index)
2406
+ const item = h.partialReasoning.get(key) || { turn: data.turn, step: data.step, index: data.index, text: '' }
2407
+ item.text += Array.isArray(data.texts) ? data.texts.join('') : String(data.text || '')
2408
+ h.partialReasoning.set(key, item)
2409
+ changed = true
2410
+ } else if (event?.type === 'assistant/message' || event?.type === 'assistant/attempt') {
2411
+ for (const [key, item] of h.partialReasoning) {
2412
+ if (item.turn === data.turn && item.step === data.step) { h.partialReasoning.delete(key); changed = true }
2413
+ }
2414
+ }
2415
+ return changed
2416
+ }
2417
+ let reasoningRenderTimer = null
2418
+ function weakStreamTrim() { return !!window.DshNetwork?.streamTrimmed?.() }
2419
+ function scheduleReasoningRender() {
2420
+ if (reasoningRenderTimer) return
2421
+ reasoningRenderTimer = setTimeout(() => {
2422
+ reasoningRenderTimer = null
2423
+ if (state.current) renderHistory()
2424
+ }, weakStreamTrim() ? 500 : 80)
2425
+ }
2426
+ function partialReasoningHtml() {
2427
+ if (weakStreamTrim()) return state.history.partialReasoning.size ? window.DshActivity?.streamNotice?.() || '' : ''
2428
+ return [...state.history.partialReasoning.values()]
2429
+ .filter(item => item.text)
2430
+ .sort((a, b) => (a.turn ?? 0) - (b.turn ?? 0) || (a.step ?? 0) - (b.step ?? 0) || (a.index ?? 0) - (b.index ?? 0))
2431
+ .map(item => window.DshActivity ? window.DshActivity.reasoning({text:item.text,live:true,key:window.DshActivity.reasoningKey(item,item.index,'live-reasoning')}) : `<div class="ds-msg assistant ds-reasoning-live"><div class="role">${esc(t('ds.role.dsh'))}</div><details open><summary>${esc(t('block.thinkingLive'))}</summary><div>${esc(item.text)}</div></details></div>`)
2432
+ .join('')
2433
+ }
2434
+ function safeJson(v) { try { return JSON.stringify(v, null, 2) } catch { return String(v) } }
2435
+ function blockHtml(b,index=0,context={}) {
2436
+ if (!b) return ''
2437
+ if ((b.type === 'tool-call' || b.type === 'tool-result') && context.suppressBlockTools) return ''
2438
+ if (typeof window !== 'undefined' && window.DshActivity) {
2439
+ const key='block:'+context.seq+':'+index
2440
+ if (b.type==='thinking'||b.type==='reasoning') return window.DshActivity.reasoning({text:b.text??b.content??'',key:window.DshActivity.reasoningKey(context,index,key)})
2441
+ 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)})})
2442
+ }
2443
+ 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'), copyCode: true, copyScope: window.DshChatCopy?.scope(state.history), copyCodeLabel: window.I18N?.lang === 'en' ? 'Copy code' : '复制代码' }) : esc(b.text ?? '')}</div>` : ''
2444
+ if (b.type === 'code') return window.DshChatCopy?.code(b.content ?? b.code ?? '', b.language || b.lang || '', { scope: window.DshChatCopy?.scope(state.history) }) || `<pre><code>${esc(b.content ?? b.code ?? '')}</code></pre>`
2445
+ if (b.type === 'file' && typeof window !== 'undefined' && window.DshChatFiles) return window.DshChatFiles.render(b)
2446
+ 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>`
2447
+ 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>`
2448
+ if (b.type === 'tool-call') return `<div>🔧 ${esc(b.name || '')}</div>`
2449
+ if (b.type === 'tool-result') return `<div>📦</div>`
2450
+ if (b.type === 'image') {
2451
+ if (b.attachment && window.DshImagePreview) return window.DshImagePreview.attachmentHtml(b.attachment, t('block.image'), state.current)
2452
+ const alt = b.name || b.filename || t('block.image')
2453
+ return `<button type="button" class="chat-image" data-chat-image aria-label="${esc(t('block.image'))}"><img alt="${esc(alt)}" src="data:${esc(b.mediaType || 'image/png')};base64,${esc(b.data || '')}" draggable="false"></button>`
2454
+ }
2455
+ return ''
2456
+ }
2457
+ function systemReminderText(blocks) {
2458
+ if (!Array.isArray(blocks)) return ''
2459
+ return blocks
2460
+ .filter(b => b && typeof b === 'object' && b.type === 'text' && String(b.text ?? '').trimStart().startsWith('<system-reminder>'))
2461
+ .map(b => String(b.text ?? ''))
2462
+ .join('\n')
2463
+ }
2464
+ function activityGroupHtml(group) {
2465
+ const items = group.items || []
2466
+ if (!items.length) return ''
2467
+ const tools = items.filter(item => item.kind === 'tool').map(item => item.entry)
2468
+ const running = !!group.running
2469
+ const failed = tools.some(entry => entry.view?.toolActivity?.error || entry.event?.data?.error)
2470
+ const body = items.map(item => item.kind === 'reasoning'
2471
+ ? window.DshActivity.reasoning({ text: item.text, key: item.key })
2472
+ : eventHtml(item.entry)).join('')
2473
+ return `<details class="chat-activity-group${failed ? ' is-error' : ''}${running ? ' is-running' : ''}" data-activity-key="activity-group:${items[0]?.seq ?? ''}"><summary><span class="activity-group-title">${esc(t('ds.activity.group', { n: items.length }))}</span>${running ? `<span class="activity-group-live"><i aria-hidden="true"></i>${esc(t('ds.activity.groupRunning'))}</span>` : ''}<span class="activity-chevron" aria-hidden="true"></span></summary><div class="activity-group-body">${body}</div></details>`
2474
+ }
2475
+
2476
+ function eventHtml(entry) {
2477
+ if (entry.view?.failureGroup) return window.DshActivity.failureGroupHtml(entry.view.failureGroup, item => eventHtml(item))
2478
+ const ev = entry.event || {}
2479
+ const data = ev.data || {}
2480
+ const type = ev.type || 'event'
2481
+ const failure = window.DshActivity?.failureHtml?.(window.DshActivity.failure(ev)) || ''
2482
+ if (entry.view?.turnResult) return failure + window.DshTurnResults.html(entry.view.turnResult)
2483
+ if (type === 'turn/start' || type === 'turn/end') return failure
2484
+ if (type === 'assistant/attempt') return window.DshActivity?.attemptHtml?.(ev) || ''
2485
+ if (entry.view?.activityGroup) return activityGroupHtml(entry.view.activityGroup)
2486
+ if (!shouldShowEvent(type, ev)) return ''
2487
+ if (window.DshActivity && (type==='tool/call'||type==='tool/result')) return window.DshActivity.toolEvent(entry)
2488
+ if (type === 'user/message' || type === 'assistant/message') {
2489
+ const msg = data.message || {}
2490
+ const role = data.role || msg.role || (type.startsWith('user') ? 'user' : 'assistant')
2491
+ const blocks = msg.content || data.content || []
2492
+ const sysText = type === 'user/message' ? systemReminderText(blocks) : ''
2493
+ if (sysText) {
2494
+ const shown = sysText.length > 400 ? sysText.slice(0, 400) + '…' : sysText
2495
+ return `<details class="event ds-tool ds-event-detail"><summary>${esc(t('ds.eventSystemReminder'))}</summary><pre>${esc(shown)}</pre></details>`
2496
+ }
2497
+ if (type === 'user/message' && !isHumanUserMessage(ev)) return ''
2498
+ const text = blocks.map((block,index)=>blockHtml(block,index,{...data,seq:entry.seq,suppressBlockTools:state.history.suppressBlockTools})).join('')
2499
+ if (!text) return ''
2500
+ return `<div class="ds-msg ${esc(role)}"><div class="role">${esc(role === 'user' ? t('ds.role.me') : t('ds.role.dsh'))}</div>${text}</div>`
2501
+ }
2502
+ if (type === 'tool/call') {
2503
+ const name = data.name || data.toolName || t('ds.toolDefault')
2504
+ const step = (data.turn != null ? ` · turn ${data.turn}` : '') + (data.step != null ? `.${data.step}` : '')
2505
+ return `<details class="ds-tool"><summary>🔧 ${esc(name)}${esc(step)}</summary><pre>${esc(safeJson(data.arguments ?? data.args ?? data.input ?? data))}</pre></details>`
2506
+ }
2507
+ if (type === 'tool/result') {
2508
+ const callId = data.callId || data.message?.source?.callId || ''
2509
+ const text = data.text || data.content || safeJson(data.message?.content ?? data)
2510
+ return `<details class="ds-tool"><summary>📦 ${esc(callId)}</summary><pre>${esc(safeJson(text))}</pre></details>`
2511
+ }
2512
+ if (type === 'approval/asked') {
2513
+ const record = state.approvalRecords?.get(data.id)
2514
+ if (record && window.DshApprovalRecords) return window.DshApprovalRecords.lineHtml(record, t)
2515
+ return `<div class="approval-event">🔐 ${esc(data.toolName || t('ds.toolDefault'))}</div>`
2516
+ }
2517
+ if (type === 'question/asked') return `<div class="ds-tool">❓ ${esc(data.question || '')}</div>`
2518
+ return `<div class="ds-tool">${esc(type)}</div>`
2519
+ }
2520
+ function canForkTurnResult() {
2521
+ const session = state.byId.get(state.current)
2522
+ return !!session && session.origin !== 'subagent' && session.formatStatus !== 'migration-required' && activeGatewayCapability('operations') === true
2523
+ }
2524
+ function bindTurnResultActions() {
2525
+ window.DshChatCopy?.bind($('history'), {
2526
+ capture: () => { const connection = captureConnection(), sessionId = state.current, history = state.history; return { history, valid: () => connection.valid() && state.current === sessionId && state.history === history } },
2527
+ copy: copyText, notice: toast,
2528
+ })
2529
+ window.DshTurnResults.bind($('history'), {
2530
+ capture: () => {
2531
+ const connection = captureConnection(), sessionId = state.current, history = state.history
2532
+ return { sessionId, entries: history.visible, key: JSON.stringify([connection.server, connection.token]), canFork: canForkTurnResult(),
2533
+ valid: () => connection.valid() && state.current === sessionId && state.history === history }
2534
+ },
2535
+ copy: copyText,
2536
+ fork: payload => rpc('session.fork', payload),
2537
+ open: async (id, context) => {
2538
+ const parent = state.byId.get(context.sessionId)
2539
+ if (!context.valid()) return
2540
+ // A confirmed fork remains usable while the session catalog is stalled.
2541
+ if (!state.byId.has(id)) {
2542
+ const branch = { ...parent, projections: parent?.projections ? { ...JSON.parse(JSON.stringify(parent.projections)), asOfSeq: 0 } : undefined,
2543
+ sessionId: id, parentSessionId: context.sessionId, origin: 'fork', running: false, blank: false }
2544
+ state.byId.set(id, branch)
2545
+ state.sessions.unshift(branch)
2546
+ renderSessions()
2547
+ }
2548
+ await openSession(id)
2549
+ }
2550
+ })
2551
+ }
2552
+
2553
+ function renderHistory(reset=false, mode='auto') {
2554
+ let prepared=window.DshActivity?.prepare(state.history.visible)||state.history.visible
2555
+ if(weakStreamTrim())prepared=prepared.filter(entry=>entry.event?.type!=='tool/call'||entry.view?.toolActivity)
2556
+ state.history.suppressBlockTools = state.history.visible.some(entry => entry.event?.type === 'tool/call')
2557
+ if(window.DshActivity?.group)prepared=window.DshActivity.group(prepared)
2558
+ const sessionRunning = !!state.byId.get(state.current)?.running
2559
+ const groups = prepared.filter(entry => entry.view?.activityGroup)
2560
+ const activeGroup = groups.at(-1)
2561
+ if (activeGroup) activeGroup.view.activityGroup.running = sessionRunning
2562
+ if (window.DshTurnResults) {
2563
+ prepared = window.DshTurnResults.decorate(prepared, state.history.visible, { sessionId: state.current, canFork: canForkTurnResult() })
2564
+ bindTurnResultActions()
2565
+ }
2566
+ if(window.DshActivity?.groupFailures)prepared=window.DshActivity.groupFailures(prepared)
2567
+ const hostError = state.runtimeErrors?.get(state.current)
2568
+ const recordedError = state.history.visible.some(entry => window.DshActivity?.failure?.(entry.event)?.message === hostError)
2569
+ const runtimeHtml = hostError && !recordedError ? window.DshActivity?.failureHtml?.(hostError) || '' : ''
2570
+ getConversationView().set(prepared,{reset,follow:mode==='bottom',live:partialReasoningHtml()+runtimeHtml,hasMore:state.history.hasMore,loading:state.history.loading,emptyLabel:t('ds.historyEmpty')})
2571
+ window.DshImagePreview?.hydrate?.($('history'))
2572
+ }
2573
+ window.applyStreamPreference=()=>{if(state.current)renderHistory(false,'auto')}
2574
+
2575
+ /* ---------------- 会话信息卡(goal / todo / 子代理) ---------------- */
2576
+ let sessionSubagentsJob = null
2577
+ function rememberSubagent(entry, parentId) {
2578
+ const childId = entry.id
2579
+ const child = state.byId.get(childId) || { sessionId: childId, cwd: state.byId.get(parentId)?.cwd || '' }
2580
+ Object.assign(child, { parentSessionId: parentId, origin: 'subagent', subagentMode: entry.mode || child.subagentMode || 'unknown' })
2581
+ if (entry.label && !child.projections?.values?.title) {
2582
+ child.projections ||= { values: {} }
2583
+ child.projections.values ||= {}
2584
+ child.projections.values.title = entry.label
2585
+ }
2586
+ state.byId.set(childId, child)
2587
+ state.subagentSessions ||= {}
2588
+ state.subagentSessions[childId] = child
2589
+ }
2590
+ async function openSubagentSession(childId, parentId, entry = {}, rootId = parentId) {
2591
+ if (!childId || childId === parentId || state.current !== rootId) return
2592
+ rememberSubagent({ ...entry, id: childId }, parentId)
2593
+ await openSession(childId)
2594
+ }
2595
+ async function loadSessionSubagents(sessionId) {
2596
+ if (sessionSubagentsJob?.sessionId === sessionId && sessionSubagentsJob.connection.valid()) return sessionSubagentsJob.promise
2597
+ const connection = captureConnection(), job = { sessionId, connection }
2598
+ job.promise = (async () => {
2599
+ const value = await rpc('subagent.list', { parentSessionId: sessionId })
2600
+ return connection.valid() ? value : null
2601
+ })()
2602
+ sessionSubagentsJob = job
2603
+ try { return await job.promise } finally { if (sessionSubagentsJob === job) sessionSubagentsJob = null }
2604
+ }
2605
+ let sessionCardsRenderGeneration = 0
2606
+ async function renderSessionCards() {
2607
+ const connection = captureConnection()
2608
+ window.DshInsights?.update()
2609
+ void refreshInsightEntry()
2610
+ const renderGeneration = ++sessionCardsRenderGeneration
2611
+ const sessionId = state.current
2612
+ const box = $('session-cards')
2613
+ const s = state.byId.get(sessionId)
2614
+ if (!box) return
2615
+ if (!s) { box.innerHTML = ''; return }
2616
+ const goal = goalOf(s)
2617
+ const todos = proj(s, 'todos')
2618
+ let html = ''
2619
+ if (goal && !isGoalTerminal(goal)) {
2620
+ const collapsed = isGoalCollapsed(sessionId, goal)
2621
+ html += `<div data-deck-kind="goal" class="ds-goal-disclosure${collapsed ? ' is-collapsed' : ''}">
2622
+ <div id="goal-panel-desktop" class="ds-card ds-goal-card${collapsed ? ' hidden' : ''}">
2623
+ <div class="ds-goal-card-head"><div class="ds-card-title">${esc(window.DshSessionDeck?.goalState(goal.phase) || goal.phase || t('goal.title'))}</div>
2624
+ <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>
2625
+ </div>
2626
+ <div class="ds-goal-obj">${esc(goal.objective || '')}</div>
2627
+ <div class="ds-goal-actions">
2628
+ ${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>`}
2629
+ <button class="ds-mini-btn" data-goal="complete">${t('goal.complete')}</button>
2630
+ <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>
2631
+ </div>
2632
+ </div>
2633
+ <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>
2634
+ </div>`
2635
+ }
2636
+ if (todos?.items?.length) {
2637
+ 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 =>
2638
+ `<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>`
2639
+ ).join('')}`}</div>`
2640
+ }
2641
+ box.innerHTML = html
2642
+ box.querySelectorAll('[data-goal]').forEach(btn =>
2643
+ btn.addEventListener('click', () => goalAction(btn.dataset.goal)))
2644
+ box.querySelectorAll('[data-goal-collapse]').forEach(btn =>
2645
+ btn.addEventListener('click', () => {
2646
+ const collapse = btn.dataset.goalCollapse === '1'
2647
+ const currentGoal = goalOf(state.byId.get(state.current))
2648
+ if (!currentGoal) return
2649
+ setGoalCollapsed(state.current, currentGoal, collapse)
2650
+ void renderSessionCards()
2651
+ requestAnimationFrame(() => box.querySelector(`[data-goal-collapse="${collapse ? '0' : '1'}"]`)?.focus())
2652
+ }))
2653
+
2654
+ if (!connection.valid() || renderGeneration !== sessionCardsRenderGeneration || state.current !== sessionId) return
2655
+ window.DshSubagents?.configure($('btn-subagents'), {
2656
+ sessionId, title: titleOf(s), activity: s.running === true ? 'running' : s.running === false ? 'inactive' : 'unknown', parentId: s.origin === 'subagent' ? s.parentSessionId : null,
2657
+ valid: () => connection.valid() && state.current === sessionId,
2658
+ read: loadSessionSubagents, remember: rememberSubagent,
2659
+ onShow: () => conversationView?.pause(), onClose: () => conversationView?.resume(),
2660
+ open: (entry, parentId) => openSubagentSession(entry.id, parentId, entry, sessionId),
2661
+ interrupt: interruptSubagent,
2662
+ })
2663
+ }
2664
+
2665
+ function setGoalPhaseLocal(phase) {
2666
+ const s = state.byId.get(state.current)
2667
+ const p = s && proj(s, 'goal')
2668
+ const goal = p && typeof p === 'object' && p.goal && typeof p.goal === 'object' ? p.goal : p
2669
+ if (!goal) return
2670
+ goal.phase = phase
2671
+ renderSessions()
2672
+ renderSessionCards()
2673
+ }
2674
+
2675
+ async function goalAction(kind) {
2676
+ const connection = captureConnection(), sessionId = state.current, history = state.history
2677
+ const valid = () => connection.valid() && state.current === sessionId && state.history === history
2678
+ const s = state.byId.get(state.current)
2679
+ const goal = goalOf(s)
2680
+ if (!goal) return toast(t('goal.none'), 'err')
2681
+ const ref = { id: goal.id, revision: goal.revision }
2682
+ if (kind === 'edit') {
2683
+ const objective = prompt(t('goal.editPrompt'), goal.objective || '')
2684
+ if (objective === null) return
2685
+ if (!objective.trim()) return toast(t('goal.cannotEmpty'), 'err')
2686
+ const result = await safeRpc('goal.edit', { sessionId, ref, objective: objective.trim() }, t('goal.updateFailed'))
2687
+ if (result == null || !valid()) return
2688
+ toast(t('goal.updated'), 'ok')
2689
+ refreshSessions()
2690
+ renderSessionCards()
2691
+ return
2692
+ }
2693
+ const map = { pause: 'goal.pause', resume: 'goal.resume', complete: 'goal.complete', clear: 'goal.clear' }
2694
+ const method = map[kind]
2695
+ if (!method) return
2696
+ if (kind === 'clear' && !confirm(t('goal.confirmClear'))) return
2697
+ if (kind === 'complete' && !confirm(t('goal.confirmComplete'))) return
2698
+ const result = await safeRpc(method, { sessionId, ref }, t('goal.actionFailed'))
2699
+ if (result == null || !valid()) return
2700
+ if (kind === 'complete') setGoalPhaseLocal('complete')
2701
+ if (kind === 'clear') setGoalPhaseLocal('cleared')
2702
+ toast(t('goal.actionSubmitted'), 'ok')
2703
+ refreshSessions()
2704
+ renderSessionCards()
2705
+ }
2706
+
2707
+ async function interruptSubagent(childId, parentId = state.current) {
2708
+ const connection = captureConnection(), rootId = state.current
2709
+ if (!confirm(t('subagent.confirmInterrupt'))) return
2710
+ const result = await safeRpc('subagent.interrupt', { parentSessionId: parentId, childSessionId: childId, mode: 'continuable' }, t('subagent.interruptFailed'))
2711
+ if (result == null || !connection.valid() || state.current !== rootId) return
2712
+ toast(t('subagent.interruptSubmitted'), 'ok')
2713
+ setTimeout(renderSessionCards, 600)
2714
+ }
2715
+
2716
+ const NO_FALLBACK_SLASH_COMMANDS = new Set(['compact', 'export'])
2717
+ const SLASH_COMMAND_TIMEOUT_MS = 20_000
2718
+ // 比插件端的 120 秒多留 5 秒,让服务端能返回确定的失败结果而非客户端先中断。
2719
+ const LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS = 125_000
2720
+
2721
+ function slashCommandName(text) {
2722
+ const match = /^\/+([^\s/]+)/.exec(String(text || '').trim())
2723
+ return match ? match[1].toLowerCase() : ''
2724
+ }
2725
+
2726
+ function sessionLogFilename(sessionId) {
2727
+ return `dsh-session-${String(sessionId).replace(/[^A-Za-z0-9_-]/g, '_')}.zip`
2728
+ }
2729
+
2730
+ async function downloadSessionExport(sessionId) {
2731
+ const connection = captureConnection()
2732
+ const url = new URL(apiUrl('/api/session.export'), location.href)
2733
+ url.searchParams.set('sessionId', sessionId)
2734
+ url.searchParams.set('includeDescendants', 'true')
2735
+ if (state.token && (state.server || !(location.pathname === '/remote' || location.pathname.startsWith('/remote/')))) url.searchParams.set('token', state.token)
2736
+ const headers = state.token ? { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() } : {}
2737
+ try {
2738
+ const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
2739
+ ? AbortSignal.timeout(LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS)
2740
+ : undefined
2741
+ const preflight = await fetch(url, { method: 'HEAD', headers, ...(signal ? { signal } : {}) })
2742
+ if (!connection.valid()) return
2743
+ if (preflight.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
2744
+ if (!preflight.ok) throw new Error('HTTP ' + preflight.status)
2745
+ const anchor = document.createElement('a')
2746
+ anchor.href = url.href
2747
+ anchor.download = sessionLogFilename(sessionId)
2748
+ document.body.appendChild(anchor)
2749
+ anchor.click()
2750
+ anchor.remove()
2751
+ toast(t('ds.exportStarted'), 'ok')
2752
+ } catch (e) {
2753
+ console.error('session export download failed', e)
2754
+ toast(t('ds.exportFailed', { msg: e?.message || '' }), 'err')
2755
+ }
2756
+ }
2757
+
2758
+ async function runSlashCommand(text, requireExecuted = false) {
2759
+ const clean = String(text || '').trim()
2760
+ if (!clean.startsWith('/') || !state.current) return false
2761
+ const sessionId = state.current, connection = captureConnection()
2762
+ const command = slashCommandName(clean)
2763
+ const noFallback = command === 'permission' || NO_FALLBACK_SLASH_COMMANDS.has(command)
2764
+ try {
2765
+ const res = await fetch(apiUrl('/remote/api/command'), {
2766
+ method: 'POST',
2767
+ headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
2768
+ body: JSON.stringify({ sessionId, line: clean, async: true }),
2769
+ signal: AbortSignal.timeout(command === 'export' ? LONG_RUNNING_SLASH_COMMAND_TIMEOUT_MS : SLASH_COMMAND_TIMEOUT_MS),
2770
+ })
2771
+ if (!connection.valid() || (state.current !== sessionId && command !== 'compact' && command !== 'export')) return !requireExecuted
2772
+ if ([404, 405].includes(res.status) && !noFallback) return false
2773
+ if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return !requireExecuted }
2774
+ if (!res.ok) throw new Error('command response unavailable')
2775
+ const data = await res.json()
2776
+ if (!connection.valid() || (state.current !== sessionId && command !== 'compact' && command !== 'export')) return !requireExecuted
2777
+ if (!data?.ok) throw new Error('command rejected')
2778
+ if (data.executed === false) {
2779
+ if (!noFallback) return false
2780
+ throw new Error('control command not executed')
2781
+ }
2782
+ if (data.executed !== true) throw new Error('unknown command result')
2783
+ if (data.accepted) {
2784
+ if (command === 'compact' || command === 'export') {
2785
+ setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
2786
+ } else {
2787
+ state.pendingCommands ||= {}
2788
+ state.pendingCommands[sessionId] = command
2789
+ const result = await waitCommandOperation(sessionId, data.operation, connection)
2790
+ if (!connection.valid() || state.current !== sessionId) return !requireExecuted
2791
+ delete state.pendingCommands[sessionId]
2792
+ if (result.executed === false && !noFallback) return false
2793
+ if (result.phase !== 'complete' || result.executed === false) throw new Error('command did not complete')
2794
+ }
2795
+ } else if (command === 'export') await downloadSessionExport(sessionId)
2796
+ else if (!requireExecuted) toast(t('ds.commandExecuted'), 'ok')
2797
+ return true
2798
+ } catch (error) {
2799
+ if (!connection.valid() || state.current !== sessionId) return !requireExecuted
2800
+ if (!requireExecuted) toast(t('ds.commandTimedOut'), 'err')
2801
+ // A lost response may follow execution. Only explicit not-executed responses can fall back.
2802
+ return !requireExecuted
2803
+ }
2804
+ }
2805
+
2806
+ async function waitCommandOperation(sessionId, initial, connection) {
2807
+ if (!initial || !initial.startedAt) throw new Error('missing operation identity')
2808
+ const deadline = Date.now() + SLASH_COMMAND_TIMEOUT_MS
2809
+ let operation = initial
2810
+ while (Date.now() < deadline) {
2811
+ if (!connection.valid() || state.current !== sessionId) throw new Error('stale command')
2812
+ if (!operation.active) {
2813
+ if (!['complete', 'failed'].includes(operation.phase)) throw new Error('unknown operation')
2814
+ return operation
2815
+ }
2816
+ await new Promise(resolve => setTimeout(resolve, 100))
2817
+ if (!connection.valid() || state.current !== sessionId) throw new Error('stale command')
2818
+ const url = apiUrl('/remote/api/command-status') + '?sessionId=' + encodeURIComponent(sessionId)
2819
+ const res = await fetch(url, { headers: { authorization: 'Bearer ' + state.token, ...clientIdHeaders() }, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) })
2820
+ if (!res.ok) throw new Error('command status unavailable')
2821
+ const body = await res.json()
2822
+ operation = body?.operation
2823
+ if (body?.ok !== true || !operation || (initial.id ? operation.id !== initial.id : operation.startedAt !== initial.startedAt)) throw new Error('operation changed')
2824
+ }
2825
+ throw new Error('command result unconfirmed')
2826
+ }
2827
+
2828
+ async function sendMessage(requestedMode = 'queue') {
2829
+ if (state.byId.get(state.current)?.origin === 'subagent') { toast('子代理记录为只读 / Subagent records are read only'); return false }
2830
+ const input = $('composer')
2831
+ const originalText = input.value, text = originalText.trim()
2832
+ if (!text || !state.current) return
2833
+ const sessionId = state.current, connection = captureConnection(), history = state.history
2834
+ const pending = sendMessage.pending ||= new Set()
2835
+ if (pending.has(history)) return
2836
+ pending.add(history)
2837
+ const valid = () => connection.valid() && state.current === sessionId && state.history === history
2838
+ try {
2839
+ state.sessionActivity.add(sessionId)
2840
+ if (await runSlashCommand(text)) { if (valid() && input.value === originalText) input.value = ''; return }
2841
+ if (!valid()) return
2842
+ setSessionRecovery('resuming')
2843
+ const v = await safeRpc('session.prompt', {
2844
+ sessionId,
2845
+ mode: requestedMode === 'steer' && state.byId.get(sessionId)?.running ? 'steer' : 'queue',
2846
+ content: [{ type: 'text', text }]
2847
+ }, '')
2848
+ if (!valid()) return
2849
+ if (v?.accepted) {
2850
+ if (input.value === originalText) input.value = ''
2851
+ setSessionRecovery('ready'); noteSessionTurnTime(sessionId, Date.now()); renderSessions(); toast(t('ds.toastSent'), 'ok')
2852
+ }
2853
+ else setSessionRecovery('error')
2854
+ } finally { pending.delete(history); window.DshWorkflow?.update() }
2855
+ }
2856
+
2857
+ async function cancelSession() {
2858
+ if (!state.current) return
2859
+ if (!confirm(t('ds.sessionStopConfirm'))) return
2860
+ const sessionId = state.current, connection = captureConnection()
2861
+ const v = await safeRpc('session.cancel', { sessionId }, t('ds.sessionStopFailed'))
2862
+ if (!connection.valid() || state.current !== sessionId) return
2863
+ if (v?.accepted) { setSessionRecovery('ready'); toast(t('ds.sessionStopRequested'), 'ok') }
2864
+ }
2865
+
2866
+ let renamePendingSessionId = null
2867
+ function renameSession(sessionId = state.current) {
2868
+ const session = state.byId.get(sessionId)
2869
+ if (!session) return
2870
+ renamePendingSessionId = sessionId
2871
+ $('rename-session-input').value = sessionTitleValue(session)
2872
+ $('modal-rename').classList.remove('hidden')
2873
+ setTimeout(() => { $('rename-session-input').focus(); $('rename-session-input').select() }, 40)
2874
+ }
2875
+ function closeRenameSession() {
2876
+ renamePendingSessionId = null
2877
+ $('modal-rename').classList.add('hidden')
2878
+ }
2879
+ async function confirmRenameSession() {
2880
+ const sessionId = renamePendingSessionId
2881
+ if (!sessionId) return
2882
+ const connection = captureConnection()
2883
+ const title = $('rename-session-input').value.trim()
2884
+ if (!title) return toast(t('ds.sessionRenameEmpty'), 'err')
2885
+ const button = $('rename-confirm')
2886
+ button.disabled = true
2887
+ setSessionRecovery('resuming')
2888
+ try {
2889
+ const value = await safeRpc('session.rename', { sessionId, title }, t('ds.sessionRenameFailed'))
2890
+ if (!connection.valid() || renamePendingSessionId !== sessionId) return
2891
+ if (value == null) { setSessionRecovery('error'); return }
2892
+ if (value != null) applyProjection(sessionId, 'title', value.title || title, value.seq)
2893
+ closeRenameSession()
2894
+ setSessionRecovery('ready')
2895
+ toast(t('ds.sessionRenamed'), 'ok')
2896
+ await refreshSessions()
2897
+ } finally {
2898
+ button.disabled = false
2899
+ }
2900
+ }
2901
+
2902
+ async function archiveCurrentSession() {
2903
+ const sessionId = state.current
2904
+ if (!sessionId || !confirm(t('ds.sessionArchiveConfirm'))) return
2905
+ const connection = captureConnection()
2906
+ const value = await safeRpc('workspace.archiveSession', { sessionId }, t('ds.toastOpFailed'))
2907
+ if (!value || !connection.valid()) return
2908
+ if (Array.isArray(value.archivedSessionIds)) state.archivedIds = value.archivedSessionIds
2909
+ toast(t('ds.sessionArchived'), 'ok')
2910
+ if (state.current === sessionId) await closeSession()
2911
+ await refreshSessions()
2912
+ }
2913
+
2914
+ function updateComposerStatus() {
2915
+ window.DshWorkflow?.update()
2916
+ const status = $('composer-status')
2917
+ if (!status) return
2918
+ const compact = activeCompaction()
2919
+ status.classList.toggle('hidden', !state.byId.get(state.current)?.running && !compact)
2920
+ status.classList.toggle('compacting', !!compact)
2921
+ const text = $('composer-status-text')
2922
+ if (text) text.textContent = compact
2923
+ ? (compact.command === 'compact'
2924
+ ? t('ds.compacting', { elapsed: compactElapsed(compact.startedAt) })
2925
+ : t('ds.commandRunning', { command: compact.command, elapsed: compactElapsed(compact.startedAt) }))
2926
+ : t('ds.composerRunning')
2927
+ updateSessionActions()
2928
+ }
2929
+ function queuePreview(item) {
2930
+ const blocks = item?.message?.content || item?.content || []
2931
+ const text = Array.isArray(blocks)
2932
+ ? blocks.filter(block => block?.type === 'text').map(block => String(block.text || '')).join(' ').trim()
2933
+ : ''
2934
+ return text || (Array.isArray(blocks) && blocks.some(block => block?.type === 'image') ? t('queue.image') : '…')
2935
+ }
2936
+ async function steerQueueItem(itemId) {
2937
+ const sessionId = state.current
2938
+ const key = `${sessionId}:${itemId}`
2939
+ const s = state.byId.get(sessionId)
2940
+ if (!sessionId || !s?.running || state.queueSteering[key]) return
2941
+ state.queueSteering[key] = true
2942
+ renderQueue()
2943
+ try {
2944
+ const v = await safeRpc('session.updateQueue', { sessionId, itemId, action: { kind: 'steer' } }, t('queue.steerFailed', { msg: '' }).replace(/:$/, '').replace(/: $/, ''))
2945
+ if (v?.accepted) toast(t('queue.steerSubmitted'), 'ok')
2946
+ } finally {
2947
+ delete state.queueSteering[key]
2948
+ renderQueue()
2949
+ }
2950
+ }
2951
+ function renderQueue() {
2952
+ const box = $('queue-dock')
2953
+ if (!box) return
2954
+ const sessionId = state.current
2955
+ const s = state.byId.get(sessionId)
2956
+ const items = (state.queues[sessionId] || []).filter(item => item?.placement === 'queued')
2957
+ box.classList.toggle('hidden', !items.length)
2958
+ box.innerHTML = items.length ? `<div class="ds-queue-dock-head"><span>⌁</span><span>${esc(t('queue.title'))} · ${items.length}</span></div><div class="ds-queue-dock-list">${items.map(item => {
2959
+ const key = `${sessionId}:${item.id}`
2960
+ const busy = !!state.queueSteering[key]
2961
+ return `<div class="ds-queue-dock-item"><span class="ds-queue-dock-preview" title="${esc(queuePreview(item))}">${esc(queuePreview(item))}</span><button type="button" class="ds-mini-btn ds-queue-dock-action" data-queue-steer="${esc(item.id)}" title="${esc(s?.running ? t('queue.steer') : t('queue.steerUnavailable'))}" ${s?.running && !busy ? '' : 'disabled'}>${busy ? '…' : esc(t('queue.steer'))}</button></div>`
2962
+ }).join('')}</div>` : ''
2963
+ box.querySelectorAll('[data-queue-steer]').forEach(button => {
2964
+ button.addEventListener('click', () => steerQueueItem(button.dataset.queueSteer))
2965
+ })
2966
+ updateComposerStatus()
2967
+ }
2968
+
2969
+ /* ---------------- 审批/提问通知卡片栈 ---------------- */
2970
+ function serverLabel() {
2971
+ const cur = currentServerEntry()
2972
+ return cur ? (cur.note || cur.url) : (state.server || location.host)
2973
+ }
2974
+ function desktopApprovalDetail(a) {
2975
+ const lines = []
2976
+ if (a?.reason) lines.push(window.DshApprovalRecords?.displayReason(a.reason) || String(a.reason))
2977
+ if (a?.arguments !== undefined) lines.push(safeJson(a.arguments))
2978
+ if (a?.callId) lines.push(`callId: ${a.callId}`)
2979
+ return lines.join('\n') || t('ds.approvalReason', { reason: '' })
2980
+ }
2981
+ function renderSessionPendingDesktop() {
2982
+ window.DshFileInbox?.render()
2983
+ const box = $('session-pending')
2984
+ if (!box) return
2985
+ const sessionId = state.current
2986
+ const items = [
2987
+ ...state.approvals.filter(a => a.sessionId === sessionId).map(a => ({ kind: 'approval', item: a })),
2988
+ ...state.questions.filter(q => q.sessionId === sessionId).map(q => ({ kind: 'question', item: q }))
2989
+ ]
2990
+ box.classList.toggle('hidden', !sessionId || !items.length)
2991
+ if (!sessionId || !items.length) { box.innerHTML = ''; return }
2992
+ 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 }) => {
2993
+ if (kind === 'approval') return `<article class="ds-notif-card" data-session-approval="${esc(item.approvalId)}">${window.DshSessionDeck?.approvalHtml(item, desktopApprovalDetail(item)) || `
2994
+ <div class="ds-notif-head">🔐 ${t('ds.approvalTitle')}</div>
2995
+ <div class="ds-notif-title">${esc(item.toolName || t('ds.toolDefault'))}</div>
2996
+ <div class="ds-notif-body">${esc(desktopApprovalDetail(item))}</div>
2997
+ <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>
2998
+ `}</article>`
2999
+ return `<button type="button" class="ds-notif-card question" data-session-question="${esc(item.rpcId)}" aria-haspopup="dialog">
3000
+ <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>
3001
+ <span class="ds-question-summary">${esc(questionSummary(item))}</span>
3002
+ </button>`
3003
+ }).join('')}</div>`
3004
+ box.querySelectorAll('[data-session-approve]').forEach(button => button.addEventListener('click', () => approveApproval(button.closest('[data-session-approval]')?.dataset.sessionApproval || '', button.dataset.sessionApprove === '1')))
3005
+ box.querySelectorAll('[data-session-question]').forEach(button => button.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === button.dataset.sessionQuestion))))
3006
+ }
3007
+ /* ---------------- 审批记录 ---------------- */
3008
+ const APPROVAL_RECORDS_KEY = 'dshApprovalRecordsV1:'
3009
+ function approvalRecordsKey() { return APPROVAL_RECORDS_KEY + encodeURIComponent(String(state.server || '')) }
3010
+ function ensureApprovalRecords() {
3011
+ if (state.approvalRecordsServer === state.server) return
3012
+ flushApprovalRecords()
3013
+ state.approvalRecordsServer = state.server
3014
+ state.approvalRecords = window.DshApprovalRecords ? window.DshApprovalRecords.restore(LS.get(approvalRecordsKey(), '[]')) : new Map()
3015
+ }
3016
+ let approvalRecordsSaveTimer = null
3017
+ let approvalRecordsPendingSave = null
3018
+ function flushApprovalRecords() {
3019
+ clearTimeout(approvalRecordsSaveTimer); approvalRecordsSaveTimer = null
3020
+ const pending = approvalRecordsPendingSave; approvalRecordsPendingSave = null
3021
+ if (pending) { try { LS.set(pending.key, pending.value) } catch {} }
3022
+ }
3023
+ function resetApprovalRecords() {
3024
+ clearTimeout(approvalRecordsSaveTimer); approvalRecordsSaveTimer = null; approvalRecordsPendingSave = null
3025
+ state.approvalRecords = new Map(); state.approvalRecordsServer = state.server
3026
+ }
3027
+ function saveApprovalRecords() {
3028
+ if (!window.DshApprovalRecords) return
3029
+ clearTimeout(approvalRecordsSaveTimer)
3030
+ approvalRecordsPendingSave = { key: approvalRecordsKey(), value: window.DshApprovalRecords.serialize(state.approvalRecords) }
3031
+ approvalRecordsSaveTimer = setTimeout(flushApprovalRecords, 800)
3032
+ }
3033
+ function collectApprovalEvent(sessionId, event) {
3034
+ ensureApprovalRecords()
3035
+ if (!window.DshApprovalRecords?.fromEvent(state.approvalRecords, sessionId, event)) return false
3036
+ saveApprovalRecords()
3037
+ return true
3038
+ }
3039
+ function collectApprovalFrame(frame) {
3040
+ ensureApprovalRecords()
3041
+ if (!window.DshApprovalRecords?.fromFrame(state.approvalRecords, frame)) return false
3042
+ saveApprovalRecords()
3043
+ renderApprovalRecordsDesktop()
3044
+ return true
3045
+ }
3046
+ function renderApprovalRecordsDesktop() {
3047
+ const box = $('ds-approval-records-list')
3048
+ if (!box) return
3049
+ ensureApprovalRecords()
3050
+ const api = window.DshApprovalRecords
3051
+ const rows = api ? api.list(state.approvalRecords, 8) : []
3052
+ const count = $('ds-approval-records-count')
3053
+ if (count) count.textContent = rows.length ? t('ds.pendingCount', { n: rows.length }) : '—'
3054
+ box.innerHTML = rows.length
3055
+ ? rows.map(record => api.recordHtml(record, t, { session: titleOf(state.byId.get(record.sessionId)) })).join('')
3056
+ : '<div class="empty">' + t('approval.recordsEmpty') + '</div>'
3057
+ }
3058
+
3059
+ function renderNotifStack() {
3060
+ const stack = $('notif-stack')
3061
+ const items = [
3062
+ ...state.approvals.map(a => ({ kind: 'approval', a })),
3063
+ ...state.questions.map(q => ({ kind: 'question', q }))
3064
+ ]
3065
+ stack.innerHTML = items.map(it => {
3066
+ if (it.kind === 'approval') {
3067
+ const a = it.a
3068
+ const reason = desktopApprovalDetail(a)
3069
+ return `<div class="ds-notif-card" data-approval="${esc(a.approvalId)}" tabindex="0">
3070
+ <div class="ds-notif-head">🔐 ${t('ds.approvalTitle')} · ${esc(serverLabel())} · ${fmtTime(a.time || Date.now())}</div>
3071
+ <div class="ds-notif-title">${esc(a.toolName || t('ds.toolDefault'))}</div>
3072
+ <div class="ds-notif-body">${esc(reason.slice(0, 500))}</div>
3073
+ <div class="ds-notif-actions">
3074
+ <button class="ds-btn allow" data-approve="1">${t('ds.allow')}</button>
3075
+ <button class="ds-btn reject" data-approve="0">${t('ds.reject')}</button>
3076
+ <button class="ds-btn" data-ignore-approval>${t('ds.ignore')}</button>
3077
+ </div>
3078
+ </div>`
3079
+ }
3080
+ const q = it.q
3081
+ const text = q.questions?.map(x => x.question).join(' / ') || ''
3082
+ return `<div class="ds-notif-card question" data-question="${esc(q.rpcId)}" tabindex="0">
3083
+ <div class="ds-notif-head">❓ ${t('ds.questionNotify')} · ${esc(serverLabel())} · ${fmtTime(q.time || Date.now())}</div>
3084
+ <div class="ds-notif-title">${esc(text.slice(0, 120))}</div>
3085
+ <div class="ds-notif-actions">
3086
+ <button class="ds-btn" data-open-question>${t('ds.submit')}</button>
3087
+ <button class="ds-btn" data-ignore-question>${t('ds.ignore')}</button>
3088
+ </div>
3089
+ </div>`
3090
+ }).join('')
3091
+ stack.querySelectorAll('[data-approve]').forEach(b => b.addEventListener('click', () => approveApproval(b.closest('[data-approval]')?.dataset.approval || '', b.dataset.approve === '1')))
3092
+ stack.querySelectorAll('[data-ignore-approval]').forEach(b => b.addEventListener('click', () => { toast(t('ds.ignored'), 'ok') }))
3093
+ stack.querySelectorAll('[data-open-question]').forEach(b => b.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === b.closest('[data-question]')?.dataset.question))))
3094
+ stack.querySelectorAll('[data-ignore-question]').forEach(b => b.addEventListener('click', () => { toast(t('ds.ignored'), 'ok') }))
3095
+ // Esc 忽略最上方卡片
3096
+ stack.querySelectorAll('.ds-notif-card').forEach(card => card.addEventListener('keydown', (e) => {
3097
+ if (e.key === 'Escape') toast(t('ds.ignored'), 'ok')
3098
+ }))
3099
+ renderSessionPendingDesktop()
3100
+ renderOverviewDesktop()
3101
+ }
3102
+ async function approveApproval(id, allow) {
3103
+ const connection = captureConnection()
3104
+ const a = state.approvals.find(x => x.approvalId === id)
3105
+ const inFlight = approveApproval.inFlight || (approveApproval.inFlight = new Set())
3106
+ if (!a || inFlight.has(id)) return
3107
+ inFlight.add(id)
3108
+ state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
3109
+ renderNotifStack()
3110
+ const restoreCard = () => {
3111
+ if (!state.approvals.some(x => x.rpcId === a.rpcId)) state.approvals = [a, ...state.approvals]
3112
+ renderNotifStack()
3113
+ }
3114
+ let ok
3115
+ try {
3116
+ ok = await respond(a.rpcId, { sessionId: a.sessionId, approvalId: a.approvalId, outcome: allow ? 'allowed-once' : 'rejected' })
3117
+ } catch (e) {
3118
+ inFlight.delete(id)
3119
+ if (!connection.valid()) { restoreCard(); return }
3120
+ restoreCard()
3121
+ if (e.message === 'AUTH') toast(t('ds.toastAuth'), 'err')
3122
+ else toast(t('ds.pendingSubmitFailed', { msg: e.message || t('ds.feedbackNetworkError') }), 'err')
3123
+ return
3124
+ }
3125
+ inFlight.delete(id)
3126
+ if (!connection.valid()) { restoreCard(); return }
3127
+ toast(ok ? (allow ? t('ds.allowed') : t('ds.rejected')) : t('ds.stale'), ok ? 'ok' : 'err')
3128
+ state.approvals = state.approvals.filter(x => x.rpcId !== a.rpcId)
3129
+ renderNotifStack()
3130
+ }
3131
+ function questionSummary(q) {
3132
+ return (q.questions || []).map(item => String(item.question || '').replace(/\[([^\]]+)\]\([^)]+\)/g, '$1').replace(/[*_`#>]/g, '')).join(' / ').replace(/\s+/g, ' ').trim().slice(0, 240)
3133
+ }
3134
+
3135
+ function questionMarkup(item) {
3136
+ const text = String(item.question || '')
3137
+ return (item.header ? `<strong>${esc(item.header)}</strong>` : '') + (window.mdToHtml ? window.mdToHtml(text, { richContent: false, fileLinks: true }) : esc(text))
3138
+ }
3139
+
3140
+ function openQuestionModal(q) {
3141
+ if (!q) return
3142
+ state.questionModal = q
3143
+ $('question-body').innerHTML = q.questions.map((item, i) => `
3144
+ <div class="ds-q-item">
3145
+ <div class="ds-q-text md">${questionMarkup(item)}</div>
3146
+ ${(item.options || []).map((o, j) => `
3147
+ <label class="ds-q-option"><input type="${item.multiSelect ? 'checkbox' : 'radio'}" name="q${i}" value="${esc(o.label)}"><span>${esc(o.label)}${o.description ? `<div class="muted">${esc(o.description)}</div>` : ''}</span></label>`).join('')}
3148
+ <textarea rows="2" placeholder="${t('ds.questionCustom')}" data-qcustom="${i}"></textarea>
3149
+ </div>`).join('')
3150
+ $('modal-question').classList.remove('hidden')
3151
+ $('question-body').scrollTop = 0
3152
+ }
3153
+ async function submitQuestion() {
3154
+ const connection = captureConnection()
3155
+ const q = state.questionModal
3156
+ if (!q) return
3157
+ const answers = q.questions.map((item, i) => {
3158
+ const sel = [...$('question-body').querySelectorAll(`input[name="q${i}"]:checked`)].map(x => x.value)
3159
+ const custom = $('question-body').querySelector(`[data-qcustom="${i}"]`)?.value?.trim()
3160
+ const ans = { id: item.id, selected: sel }
3161
+ if (custom) ans.custom = custom
3162
+ if (!sel.length && !custom) return null
3163
+ return ans
3164
+ }).filter(Boolean)
3165
+ if (!answers.length) return toast(t('ds.questionNeedAnswer'), 'err')
3166
+ let ok
3167
+ try {
3168
+ ok = await respond(q.rpcId, { sessionId: q.sessionId, answer: { answers } })
3169
+ } catch (e) {
3170
+ if (!connection.valid()) return
3171
+ if (e.message === 'AUTH') toast(t('ds.toastAuth'), 'err')
3172
+ else toast(t('ds.pendingSubmitFailed', { msg: e.message || t('ds.feedbackNetworkError') }), 'err')
3173
+ return
3174
+ }
3175
+ if (!connection.valid()) return
3176
+ if (ok) {
3177
+ toast(t('ds.questionSubmitted'), 'ok')
3178
+ if (state.questionModal === q) { $('modal-question').classList.add('hidden'); state.questionModal = null }
3179
+ state.questions = state.questions.filter(x => x.rpcId !== q.rpcId)
3180
+ renderNotifStack()
3181
+ } else toast(t('ds.stale'), 'err')
3182
+ }
3183
+
3184
+ /* ---------------- 文件传输 ---------------- */
3185
+ function fsApiUrl(sub, params = {}) {
3186
+ const u = new URL(apiUrl('/fs' + sub), location.href)
3187
+ for (const [k, v] of Object.entries(params)) {
3188
+ if (v != null && v !== '') u.searchParams.set(k, v)
3189
+ }
3190
+ return u.href
3191
+ }
3192
+ function fsHeaders() {
3193
+ return { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
3194
+ }
3195
+
3196
+ /** Local image paths inside Markdown: resolve relative to the open session workspace. */
3197
+ async function chatImageAttachment(attachment, sessionId) {
3198
+ const connection = captureConnection()
3199
+ if (!sessionId || sessionId !== state.current || !connection.valid()) throw new Error('stale image')
3200
+ const ref = typeof attachment === 'string' ? { attachmentId: attachment } : attachment
3201
+ if (!ref || !/^(?:sha256:)?[a-f0-9]{64}$/.test(String(ref.attachmentId || ''))) throw new Error('invalid image attachment')
3202
+ // DSH modern RPC validates the whole attachment reference, not only its id.
3203
+ const payload = { sessionId, attachment: {
3204
+ attachmentId: ref.attachmentId,
3205
+ ...(ref.mediaType === undefined ? {} : { mediaType: ref.mediaType }),
3206
+ ...(ref.bytes === undefined ? {} : { bytes: ref.bytes }),
3207
+ ...(ref.width === undefined ? {} : { width: ref.width }),
3208
+ ...(ref.height === undefined ? {} : { height: ref.height }),
3209
+ ...(ref.name ? { name: ref.name } : {}),
3210
+ } }
3211
+ const result = await rpc('session.attachment', payload, 120000)
3212
+ if (!connection.valid() || state.current !== sessionId) throw new Error('stale image')
3213
+ return result
3214
+ }
3215
+ function chatImageRequest(pathValue) {
3216
+ const value = String(pathValue || '').trim()
3217
+ if (!value) return null
3218
+ let target = value
3219
+ if (!/^(?:[A-Za-z]:[\\/]|\\\\|\/|~[\\/])/.test(value)) {
3220
+ const root = state.byId.get(state.current)?.cwd || ''
3221
+ if (root) target = root.replace(/[\\/]+$/, '') + (root.includes('\\') ? '\\' : '/') + value.replace(/^\.?[\\/]+/, '')
3222
+ }
3223
+ return { url: fsApiUrl('/file', { path: target }), headers: fsHeaders() }
3224
+ }
3225
+ function fsParent(p) {
3226
+ const meta = fsPathMeta(p)
3227
+ if (!meta.value) return null
3228
+ if (meta.root && fsPathEqual(meta.value, meta.root)) return meta.root
3229
+ const idx = meta.value.lastIndexOf(meta.separator)
3230
+ if (idx < 0) return meta.root || null
3231
+ const parent = meta.value.slice(0, idx)
3232
+ return meta.root && parent.length < meta.root.length ? meta.root : (parent || meta.root)
3233
+ }
3234
+ function fsJoin(dir, name) {
3235
+ const meta = fsPathMeta(dir)
3236
+ if (!meta.value) return String(name || '')
3237
+ return meta.value.endsWith(meta.separator) ? meta.value + name : meta.value + meta.separator + name
3238
+ }
3239
+ function fsPathMeta(input) {
3240
+ const source = String(input || '').trim()
3241
+ const windows = /^[A-Za-z]:(?:[\\/]|$)/.test(source) || /^[\\/]{2}[^\\/]+[\\/][^\\/]+/.test(source) || source.includes('\\')
3242
+ if (!windows) {
3243
+ let value = source.replace(/\/+/g, '/')
3244
+ const root = value.startsWith('/') ? '/' : ''
3245
+ if (root && value.length > root.length) value = value.replace(/\/+$/, '')
3246
+ return { value, root, separator: '/', windows: false }
3247
+ }
3248
+ let value = source.replace(/\//g, '\\')
3249
+ const unc = /^\\{2,}/.test(value)
3250
+ value = unc
3251
+ ? '\\\\' + value.replace(/^\\+/, '').replace(/\\+/g, '\\')
3252
+ : value.replace(/\\+/g, '\\')
3253
+ let root = ''
3254
+ if (unc) {
3255
+ const parts = value.slice(2).split('\\').filter(Boolean)
3256
+ root = parts.length >= 2 ? `\\\\${parts[0]}\\${parts[1]}` : value
3257
+ } else {
3258
+ const drive = /^([A-Za-z]:)/.exec(value)
3259
+ if (drive) {
3260
+ root = drive[1] + '\\'
3261
+ if (value === drive[1]) value = root
3262
+ }
3263
+ }
3264
+ if (root && value.length > root.length) value = value.replace(/\\+$/, '')
3265
+ return { value, root, separator: '\\', windows: true }
3266
+ }
3267
+ function fsPathKey(value) {
3268
+ const meta = fsPathMeta(value)
3269
+ return meta.windows ? meta.value.toLowerCase() : meta.value
3270
+ }
3271
+ function fsPathEqual(left, right) { return fsPathKey(left) === fsPathKey(right) }
3272
+ function fsPathInside(candidate, root) {
3273
+ const child = fsPathMeta(candidate)
3274
+ const boundary = fsPathMeta(root)
3275
+ if (!child.value || !boundary.value || child.windows !== boundary.windows) return false
3276
+ const childKey = child.windows ? child.value.toLowerCase() : child.value
3277
+ const rootKey = boundary.windows ? boundary.value.toLowerCase() : boundary.value
3278
+ if (childKey === rootKey) return true
3279
+ const prefix = rootKey.endsWith(boundary.separator) ? rootKey : rootKey + boundary.separator
3280
+ return childKey.startsWith(prefix)
3281
+ }
3282
+ function resetFsForServerDesktop() {
3283
+ state.fs.path = null
3284
+ state.fs.initial = null
3285
+ state.fs.loaded = false
3286
+ state.fs.roots = []
3287
+ state.fs.rootIndex = 0
3288
+ const select = $('fs-root')
3289
+ if (select) select.classList.add('hidden')
3290
+ }
3291
+ async function openWorkspaceModal() {
3292
+ const connection = captureConnection()
3293
+ if (!state.token) { toast(t('ds.toastAuth'), 'err'); showView('view-settings'); return }
3294
+ if (!state.fs.path) await loadFs(null, true)
3295
+ if (!connection.valid()) return
3296
+ $('workspace-parent-path').textContent = state.fs.path || '~'
3297
+ $('workspace-name').value = ''
3298
+ $('modal-workspace').classList.remove('hidden')
3299
+ void loadSessionPresets('workspace')
3300
+ setTimeout(() => $('workspace-name').focus(), 50)
3301
+ }
3302
+ function closeWorkspaceModal() { $('modal-workspace').classList.add('hidden') }
3303
+ async function createWorkspace() {
3304
+ if (createWorkspace.busy) return
3305
+ const preset = window.DshSessionPresets.selection($('workspace-agent-preset'))
3306
+ if (!preset.valid) return toast(window.DshSessionPresets.staleMessage(), 'err')
3307
+ const name = $('workspace-name').value.trim()
3308
+ if (!name) { toast(t('ds.workspaceNameRequired'), 'err'); $('workspace-name').focus(); return }
3309
+ const connection = captureConnection()
3310
+ createWorkspace.busy = true
3311
+ const parent = state.fs.path || ''
3312
+ const button = $('workspace-create')
3313
+ button.disabled = true
3314
+ try {
3315
+ const res = await fetch(fsApiUrl('/mkdir', { path: parent, name }), { method: 'POST', headers: fsHeaders() })
3316
+ if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
3317
+ const data = await res.json().catch(() => ({}))
3318
+ if (!connection.valid()) return
3319
+ if (!res.ok) {
3320
+ const msg = data.error === 'exists' ? t('ds.workspaceExists') : data.error === 'bad-name' ? t('ds.workspaceInvalidName') : data.error || ('HTTP ' + res.status)
3321
+ throw new Error(msg)
3322
+ }
3323
+ closeWorkspaceModal()
3324
+ await loadFs(parent || null, true)
3325
+ if (!connection.valid()) return
3326
+ let workspace = null
3327
+ try {
3328
+ const created = await rpc('workspace.create', { path: data.path })
3329
+ if (!connection.valid()) return
3330
+ workspace = created?.workspace || null
3331
+ } catch {}
3332
+ if (!connection.valid()) return
3333
+ if (workspace?.workspaceId) {
3334
+ state.workspaces = [...state.workspaces.filter(item => item.workspaceId !== workspace.workspaceId), workspace]
3335
+ }
3336
+ const sessionPayload = workspace?.workspaceId ? { workspaceId: workspace.workspaceId } : { cwd: data.path }
3337
+ const v = await safeRpc('session.create', { ...sessionPayload, ...preset.payload }, t('ds.toastOpFailed'))
3338
+ if (!connection.valid()) return
3339
+ await refreshSessions()
3340
+ if (!connection.valid()) return
3341
+ if (v?.sessionId) {
3342
+ if (workspace?.workspaceId) LS.set('lastNewSessionWorkspaceV1', workspace.workspaceId)
3343
+ toast(t('ds.workspaceCreated'), 'ok')
3344
+ openSession(v.sessionId)
3345
+ } else {
3346
+ toast(t('ds.workspaceCreatedNoSession'), 'ok')
3347
+ }
3348
+ } catch (e) {
3349
+ if (!connection.valid()) return
3350
+ toast(`${t('ds.workspaceCreateFailed')}:${e.message || t('ds.feedbackNetworkError')}`, 'err')
3351
+ } finally {
3352
+ createWorkspace.busy = false
3353
+ button.disabled = false
3354
+ }
3355
+ }
3356
+ async function loadFs(dir, silent) {
3357
+ const connection = captureConnection(), request = ++filesRequest
3358
+ const valid = () => connection.valid() && request === filesRequest
3359
+ if (!state.token) {
3360
+ $('fs-path').textContent = t('ds.toastAuth')
3361
+ $('fs-list').innerHTML = `<div class="ds-empty">${t('ds.toastAuth')}</div>`
3362
+ return
3363
+ }
3364
+ const target = dir ?? state.fs.path ?? ''
3365
+ if (!silent) {
3366
+ $('fs-list').innerHTML = `<div class="ds-empty">${t('ds.loading')}</div>`
3367
+ $('fs-path').textContent = target ? '…' + target.slice(-40) : t('ds.loading')
3368
+ }
3369
+ try {
3370
+ const res = await fetch(fsApiUrl('/list', target ? { path: target } : {}), { headers: fsHeaders() })
3371
+ if (!valid()) return
3372
+ if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
3373
+ const data = await res.json().catch(() => ({}))
3374
+ if (!valid()) return
3375
+ if (!res.ok || !Array.isArray(data.entries)) throw new Error(data.error || ('HTTP ' + res.status))
3376
+ state.fs.path = data.path
3377
+ if (!state.fs.initial) state.fs.initial = data.path
3378
+ if (Array.isArray(data.roots) && data.roots.length) state.fs.roots = data.roots.map(value => String(value || '')).filter(Boolean)
3379
+ if (!state.fs.roots.length) state.fs.roots = [data.path]
3380
+ const rootIndex = state.fs.roots.findIndex(root => fsPathInside(data.path, root))
3381
+ if (rootIndex >= 0) state.fs.rootIndex = rootIndex
3382
+ state.fs.loaded = true
3383
+ renderFsRootsDesktop()
3384
+ $('fs-path').textContent = data.path
3385
+ $('fs-list').innerHTML = (data.entries || []).map(e => `
3386
+ <div class="ds-fs-row" data-fs-path="${esc(e.path || fsJoin(data.path, e.name))}" data-fs-dir="${e.type === 'dir' ? '1' : '0'}">
3387
+ <span class="ds-fs-type">${desktopFsIconSvg(e.type === 'dir')}</span>
3388
+ <span class="ds-fs-name">${esc(e.name)}</span>
3389
+ <span class="ds-fs-size">${e.type === 'dir' ? '' : fmtSize(e.size)}</span>
3390
+ </div>`).join('') || `<div class="ds-empty">${t('ds.fsEmpty')}</div>`
3391
+ $('fs-list').querySelectorAll('[data-fs-path]').forEach(row => row.addEventListener('click', () => {
3392
+ if (row.dataset.fsDir === '1') loadFs(row.dataset.fsPath)
3393
+ else window.open(fsApiUrl('/file', { path: row.dataset.fsPath, token: state.token }), '_blank')
3394
+ }))
3395
+ } catch (e) {
3396
+ if (!valid()) return
3397
+ $('fs-path').textContent = target || '~'
3398
+ $('fs-list').innerHTML = `<div class="ds-empty">${esc(e.message || t('ds.toastConnFailed'))}</div>`
3399
+ }
3400
+ }
3401
+
3402
+ function renderFsRootsDesktop() {
3403
+ const select = $('fs-root')
3404
+ if (!select) return
3405
+ select.classList.toggle('hidden', state.fs.roots.length <= 1)
3406
+ select.innerHTML = state.fs.roots.map((root, index) => `<option value="${index}"${index === state.fs.rootIndex ? ' selected' : ''}>${esc(root)}</option>`).join('')
3407
+ }
3408
+
3409
+ function desktopFsIconSvg(isDir) {
3410
+ return isDir
3411
+ ? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3.5 6.5h6l2 2H20a1 1 0 0 1 1 1v8.5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7.5a1 1 0 0 1 .5-1Z"/></svg>'
3412
+ : '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5h8l4 4V20a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4.5a1 1 0 0 1 1-1Z"/><path d="M14 3.5v4h4M8 13h8M8 16h6"/></svg>'
3413
+ }
3414
+ function fsUp() {
3415
+ if (!state.fs.path || !state.fs.initial) return
3416
+ const parent = fsParent(state.fs.path)
3417
+ if (fsPathEqual(state.fs.path, state.fs.initial) || !fsPathInside(parent, state.fs.initial)) return
3418
+ loadFs(parent)
3419
+ }
3420
+
3421
+ /* ---------------- 工作台绑定 / 项目会话 ---------------- */
3422
+ function wbPathKey(p) {
3423
+ let value = String(p || '').replace(/\\/g, '/').replace(/\/+/g, '/')
3424
+ if (value.length > 1) value = value.replace(/\/+$/, '')
3425
+ const windows = /^[A-Za-z]:\//.test(value) || /Windows/i.test(navigator.platform || navigator.userAgent || '')
3426
+ return windows ? value.toLowerCase() : value
3427
+ }
3428
+ function wbBaseName(p) {
3429
+ const value = String(p || '').replace(/[\\/]+$/, '')
3430
+ return value.split(/[\\/]/).pop() || value
3431
+ }
3432
+ function workspaceItems() {
3433
+ return (state.workspaces || []).filter(w => w && typeof w.workspaceId === 'string' && w.workspaceId && typeof w.path === 'string' && w.path)
3434
+ }
3435
+ function workspaceById(workspaceId) {
3436
+ return workspaceItems().find(w => w.workspaceId === workspaceId) || null
3437
+ }
3438
+ function workspaceName(workspace) {
3439
+ return String(workspace?.title || wbBaseName(workspace?.path) || workspace?.path || '').trim()
3440
+ }
3441
+ function workspaceOptionLabel(workspace) {
3442
+ const name = workspaceName(workspace)
3443
+ return workspace.path && workspace.path !== name ? `${name} — ${workspace.path}` : name
3444
+ }
3445
+ function workspaceOptionsHtml(selected = '') {
3446
+ return workspaceItems().map(workspace => `<option value="${esc(workspace.workspaceId)}"${workspace.workspaceId === selected ? ' selected' : ''}>${esc(workspaceOptionLabel(workspace))}</option>`).join('')
3447
+ }
3448
+ function wbStrictInside(pathValue, rootValue) {
3449
+ const pathKey = wbPathKey(pathValue)
3450
+ const rootKey = wbPathKey(rootValue)
3451
+ if (!pathKey || !rootKey || pathKey === rootKey) return false
3452
+ return pathKey.startsWith(rootKey.endsWith('/') ? rootKey : rootKey + '/')
3453
+ }
3454
+ function wbJoin(root, name) {
3455
+ const raw = String(root || '')
3456
+ const separator = raw.includes('\\') ? '\\' : '/'
3457
+ return raw.replace(/[\\/]+$/, '') + separator + String(name || '')
3458
+ }
3459
+ function wbFsParent(p) {
3460
+ if (!p) return null
3461
+ const raw = String(p)
3462
+ const separator = raw.includes('\\') ? '\\' : '/'
3463
+ const index = raw.lastIndexOf(separator)
3464
+ if (index <= 0 || /^[A-Za-z]:$/.test(raw.slice(0, index))) return null
3465
+ return raw.slice(0, index)
3466
+ }
3467
+ async function wbGateway(method, pathname, body) {
3468
+ const options = { method, headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() } }
3469
+ if (body !== undefined) {
3470
+ options.headers['content-type'] = 'application/json'
3471
+ options.body = JSON.stringify(body)
3472
+ }
3473
+ const res = await fetch(apiUrl(pathname), options)
3474
+ if (res.status === 401) throw new Error('AUTH')
3475
+ const data = await res.json().catch(() => ({}))
3476
+ if (!res.ok) throw new Error(data.error || ('HTTP ' + res.status))
3477
+ return data
3478
+ }
3479
+ const WORKBENCH_ORDER_CACHE_KEY = 'workbenchOrderV1'
3480
+ function workbenchOrderScope() { return String(state.server || location.origin || 'default') }
3481
+ function workbenchOrderStore() {
3482
+ let value = null
3483
+ try { value = JSON.parse(LS.get(WORKBENCH_ORDER_CACHE_KEY, '{}')) } catch {}
3484
+ if (!value || typeof value !== 'object') value = {}
3485
+ if (!value.scopes || typeof value.scopes !== 'object') value.scopes = {}
3486
+ return value
3487
+ }
3488
+ function workbenchOrderScopeValue() {
3489
+ const store = workbenchOrderStore()
3490
+ const key = workbenchOrderScope()
3491
+ if (!store.scopes[key] || typeof store.scopes[key] !== 'object') store.scopes[key] = {}
3492
+ return { store, value: store.scopes[key] }
3493
+ }
3494
+ function orderedItems(items, ids, getId) {
3495
+ const source = Array.isArray(items) ? items : []
3496
+ const byId = new Map(source.map(item => [String(getId(item)), item]))
3497
+ const result = []
3498
+ const used = new Set()
3499
+ for (const id of Array.isArray(ids) ? ids : []) {
3500
+ const key = String(id)
3501
+ const item = byId.get(key)
3502
+ if (item && !used.has(key)) { result.push(item); used.add(key) }
3503
+ }
3504
+ for (const item of source) {
3505
+ const key = String(getId(item))
3506
+ if (!used.has(key)) { result.push(item); used.add(key) }
3507
+ }
3508
+ return result
3509
+ }
3510
+ function orderedWorkspaceItems(items) {
3511
+ const { value } = workbenchOrderScopeValue()
3512
+ return orderedItems(items, value.workspaceIds, item => item.workspaceId)
3513
+ }
3514
+ function orderedWorkspaceSessions(workspaceId, items) {
3515
+ const { value } = workbenchOrderScopeValue()
3516
+ return orderedItems(items, value.sessionIds?.[String(workspaceId)], item => item.sessionId)
3517
+ }
3518
+ function saveWorkbenchOrder(mutator) {
3519
+ const { store, value } = workbenchOrderScopeValue()
3520
+ mutator(value)
3521
+ LS.set(WORKBENCH_ORDER_CACHE_KEY, JSON.stringify(store))
3522
+ }
3523
+ function commitWorkspaceOrder(order) {
3524
+ saveWorkbenchOrder(value => { value.workspaceIds = order.map(String) })
3525
+ renderWorkbench()
3526
+ toast(t('ds.wbOrderSaved'), 'ok')
3527
+ }
3528
+ function commitWorkspaceSessionOrder(workspaceId, order) {
3529
+ if (!workspaceId) return
3530
+ saveWorkbenchOrder(value => {
3531
+ value.sessionIds ||= {}
3532
+ value.sessionIds[String(workspaceId)] = order.map(String)
3533
+ })
3534
+ renderWorkbench()
3535
+ toast(t('ds.wbOrderSaved'), 'ok')
3536
+ }
3537
+ async function refreshWorkbench({ silent = false, discover = false } = {}) {
3538
+ const connection = captureConnection(), request = ++workbenchRequest
3539
+ const valid = () => connection.valid() && request === workbenchRequest
3540
+ const sharedRead = (name, read) => window.DshNetwork?.shareRead ? window.DshNetwork.shareRead(JSON.stringify([connection.server, connection.token, name]), read) : read()
3541
+ if (!state.token) { renderWorkbench(); return }
3542
+ const workspaceRead = sharedRead('workspace.list', () => connection.valid() ? safeRpc('workspace.list', {}, '') : null)
3543
+ let wb = null
3544
+ try {
3545
+ wb = await sharedRead('workbench', () => connection.valid() ? wbGateway('GET', '/workbench') : null)
3546
+ if (!valid()) return
3547
+ state.wb.apiMissing = false
3548
+ } catch (e) {
3549
+ if (!valid()) return
3550
+ if (e.message === 'AUTH') { toast(t('ds.toastAuth'), 'err'); return }
3551
+ if (!silent) toast(t('wb.loadFailed', { msg: e.message }), 'err')
3552
+ if (!state.wb.bound && /404/.test(e.message)) state.wb.apiMissing = true
3553
+ }
3554
+ const wl = await workspaceRead
3555
+ if (!valid()) return
3556
+ if(wl){
3557
+ state.archivedIds = Array.isArray(wl.archivedSessionIds) ? wl.archivedSessionIds : []
3558
+ state.workspaces = Array.isArray(wl.items) ? wl.items.slice() : []
3559
+ }
3560
+ if (!wb) { renderWorkbench(); renderSessions(); return }
3561
+ if (!wb.bound) {
3562
+ state.wb = { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false }
3563
+ renderWorkbench()
3564
+ renderSessions()
3565
+ return
3566
+ }
3567
+ state.wb.bound = true
3568
+ state.wb.path = wb.path || ''
3569
+ state.wb.title = wb.title || ''
3570
+ if (!wl) { renderWorkbench(); renderSessions(); return }
3571
+ const items = Array.isArray(wl.items) ? wl.items.slice() : []
3572
+ if (discover) try {
3573
+ const listRes = await fetch(fsApiUrl('/list', { path: state.wb.path }), { headers: fsHeaders() })
3574
+ if (!valid()) return
3575
+ if (listRes.ok) {
3576
+ const listData = await listRes.json().catch(() => ({}))
3577
+ if (!valid()) return
3578
+ if (Array.isArray(listData.entries)) {
3579
+ const diskDirs = new Set(listData.entries.filter(e => e.type === 'dir').map(e => wbPathKey(wbJoin(state.wb.path, e.name))))
3580
+ for (let i = items.length - 1; i >= 0; i--) {
3581
+ if (!diskDirs.has(wbPathKey(items[i].path))) items.splice(i, 1)
3582
+ }
3583
+ const have = new Set(items.map(w => wbPathKey(w.path)))
3584
+ for (const entry of listData.entries) {
3585
+ if (entry.type !== 'dir') continue
3586
+ const projectPath = wbJoin(state.wb.path, entry.name)
3587
+ if (have.has(wbPathKey(projectPath))) continue
3588
+ try {
3589
+ const created = await rpc('workspace.create', { path: projectPath })
3590
+ if (!valid()) return
3591
+ if (created?.workspace) {
3592
+ items.push(created.workspace)
3593
+ state.workspaces.push(created.workspace)
3594
+ have.add(wbPathKey(projectPath))
3595
+ }
3596
+ } catch {}
3597
+ if (!valid()) return
3598
+ }
3599
+ }
3600
+ }
3601
+ } catch {}
3602
+ if (!valid()) return
3603
+ state.wb.projects = orderedWorkspaceItems(items
3604
+ .filter(w => wbStrictInside(w.path, state.wb.path))
3605
+ .sort((a, b) => String(a.title || wbBaseName(a.path)).localeCompare(String(b.title || wbBaseName(b.path)), 'zh-CN', { numeric: true })))
3606
+ renderWorkbench()
3607
+ renderSessions()
3608
+ }
3609
+ function renderWorkbench() {
3610
+ const box = $('workbench-box')
3611
+ if (!box) return
3612
+ const unbound = $('wb-unbound')
3613
+ const bound = $('wb-bound')
3614
+ const hint = $('wb-api-hint')
3615
+ if (!state.wb.bound) {
3616
+ unbound.classList.remove('hidden')
3617
+ bound.classList.add('hidden')
3618
+ hint?.classList.toggle('hidden', !state.wb.apiMissing)
3619
+ return
3620
+ }
3621
+ unbound.classList.add('hidden')
3622
+ bound.classList.remove('hidden')
3623
+ $('wb-head-text').textContent = t('wb.bound', { title: state.wb.title || wbBaseName(state.wb.path) })
3624
+ $('wb-head').setAttribute('aria-expanded', state.wb.expanded ? 'true' : 'false')
3625
+ $('wb-caret').textContent = state.wb.expanded ? '▾' : '▸'
3626
+ const panel = $('wb-panel')
3627
+ panel.classList.toggle('hidden', !state.wb.expanded)
3628
+ if (!state.wb.expanded) return
3629
+ const projects = orderedWorkspaceItems(state.wb.projects || [])
3630
+ const archivedSet = new Set(state.archivedIds || [])
3631
+ let html = `<div class="ds-wb-panel-title">${esc(t('wb.projects'))}</div>`
3632
+ html += projects.length ? projects.map(w => {
3633
+ const id = String(w.workspaceId || '')
3634
+ const sessions = orderedWorkspaceSessions(id, (w.sessionIds || []).map(sid => state.byId.get(sid)).filter(isVisibleSession).filter(s => !archivedSet.has(s.sessionId)).sort((a, b) => sessionSortTime(b) - sessionSortTime(a)))
3635
+ const open = state.wb.open === id
3636
+ return `<div class="ds-wb-project ${open ? 'open' : ''}" data-wb-project="${esc(id)}" data-motion-key="${esc(id)}">
3637
+ <button type="button" class="ds-wb-project-head" data-wb-head="${esc(id)}">
3638
+ <span class="ds-wb-drag-handle" data-reorder-handle aria-hidden="true">⠿</span>
3639
+ <span class="ds-wb-caret" aria-hidden="true">${open ? '▾' : '▸'}</span>
3640
+ <span class="ds-wb-project-title" title="${esc(w.path)}">${esc(w.title || wbBaseName(w.path) || short(id))}</span>
3641
+ <span class="ds-wb-project-count">${sessions.length}</span>
3642
+ </button>
3643
+ <div class="ds-wb-project-body ${open ? '' : 'hidden'}">
3644
+ <button type="button" class="ds-mini-btn ds-wb-new-session" data-wb-new="${esc(id)}">+ ${esc(t('wb.newSession'))}</button>
3645
+ ${sessions.length ? sessions.map(s => `<button type="button" class="ds-wb-session ${state.current === s.sessionId ? 'current' : ''}" data-wb-session="${esc(s.sessionId)}" data-motion-key="${esc(s.sessionId)}"><span class="ds-wb-session-drag-handle" data-reorder-handle aria-hidden="true">⠿</span><span class="ds-wb-session-dot ${s.running ? 'running' : ''}"></span><span class="ds-wb-session-title">${esc(sessionLabelOf(s))}</span></button>`).join('') : `<div class="ds-wb-session-empty">${esc(t('wb.noSessions'))}</div>`}
3646
+ </div>
3647
+ </div>`
3648
+ }).join('') : `<div class="ds-wb-empty">${esc(t('wb.noProjects'))}</div>`
3649
+ html += `<button type="button" class="ds-mini-btn ds-wb-unbind-panel" data-wb-unbind-panel>${esc(t('wb.unbind'))}</button>`
3650
+ if (window.DshMotion?.relayout) {
3651
+ window.DshMotion.relayout(panel, '.ds-wb-project', () => { panel.innerHTML = html })
3652
+ } else panel.innerHTML = html
3653
+ window.DshMotion?.list(panel, '.ds-wb-session')
3654
+ window.DshMotion?.bindLongPressReorder(panel, '.ds-wb-project', {
3655
+ handleSelector: '.ds-wb-project-head',
3656
+ excludeSelector: '[data-wb-new]',
3657
+ onCommit: ({ order }) => commitWorkspaceOrder(order)
3658
+ })
3659
+ window.DshMotion?.bindLongPressReorder(panel, '.ds-wb-session', {
3660
+ groupSelector: '.ds-wb-project',
3661
+ handleSelector: '.ds-wb-session',
3662
+ onCommit: ({ item, order }) => commitWorkspaceSessionOrder(item.closest('[data-wb-project]')?.dataset.wbProject, order)
3663
+ })
3664
+ panel.querySelectorAll('[data-wb-head]').forEach(button => button.addEventListener('click', () => {
3665
+ state.wb.open = state.wb.open === button.dataset.wbHead ? null : button.dataset.wbHead
3666
+ renderWorkbench()
3667
+ }))
3668
+ panel.querySelectorAll('[data-wb-new]').forEach(button => button.addEventListener('click', async () => {
3669
+ void openNewSessionModal(button.dataset.wbNew)
3670
+ }))
3671
+ panel.querySelectorAll('[data-wb-session]').forEach(button => button.addEventListener('click', () => openSession(button.dataset.wbSession)))
3672
+ panel.querySelectorAll('[data-wb-unbind-panel]').forEach(button => button.addEventListener('click', unbindWorkbench))
3673
+ }
3674
+ function renderNewSessionWorkspace(preferredId = '') {
3675
+ const items = workspaceItems()
3676
+ const select = $('new-session-workspace')
3677
+ if (!select) return
3678
+ const current = workspaceById(preferredId || select.value)?.workspaceId || items[0]?.workspaceId || ''
3679
+ select.innerHTML = workspaceOptionsHtml(current)
3680
+ select.disabled = !items.length
3681
+ const workspace = workspaceById(select.value)
3682
+ $('new-session-workspace-name').textContent = workspace ? workspaceName(workspace) : ''
3683
+ $('new-session-workspace-path').textContent = workspace?.path || ''
3684
+ $('new-session-empty').classList.toggle('hidden', !!items.length)
3685
+ $('new-session-create').disabled = !workspace
3686
+ }
3687
+ function loadSessionPresets(prefix) {
3688
+ return window.DshSessionPresets.open({select:$(prefix+'-agent-preset'),hint:$(prefix+'-agent-preset-hint'),rpc,connection:captureConnection()})
3689
+ }
3690
+ async function openNewSessionModal(preferredWorkspace = '') {
3691
+ if (!state.token) return showView('view-settings')
3692
+ if (!workspaceItems().length) await refreshWorkbench({ silent: true })
3693
+ renderNewSessionWorkspace(typeof preferredWorkspace === 'string' && preferredWorkspace || LS.get('lastNewSessionWorkspaceV1', ''))
3694
+ void loadSessionPresets('new-session')
3695
+ $('modal-new-session').classList.remove('hidden')
3696
+ setTimeout(() => $('new-session-workspace')?.focus(), 50)
3697
+ }
3698
+ function closeNewSessionModal() { $('modal-new-session').classList.add('hidden') }
3699
+ async function createSessionInWorkspace() {
3700
+ if (createSessionInWorkspace.busy) return
3701
+ const connection = captureConnection()
3702
+ const workspaceId = $('new-session-workspace').value
3703
+ if (!workspaceById(workspaceId)) return toast(t('ds.newSessionChooseWorkspace'), 'err')
3704
+ const preset = window.DshSessionPresets.selection($('new-session-agent-preset'))
3705
+ if (!preset.valid) return toast(window.DshSessionPresets.staleMessage(), 'err')
3706
+ createSessionInWorkspace.busy = true
3707
+ const button = $('new-session-create')
3708
+ button.disabled = true
3709
+ try {
3710
+ const value = await safeRpc('session.create', { workspaceId, ...preset.payload }, '')
3711
+ if (!connection.valid() || !value?.sessionId) return
3712
+ LS.set('lastNewSessionWorkspaceV1', workspaceId)
3713
+ closeNewSessionModal()
3714
+ const workspace = workspaceById(workspaceId)
3715
+ const session = { sessionId: value.sessionId, cwd: workspace?.path || '', running: false, projections: { values: {} } }
3716
+ state.byId.set(session.sessionId, session)
3717
+ state.sessions.unshift(session)
3718
+ void openSession(session.sessionId)
3719
+ void refreshSessions()
3720
+ } finally {
3721
+ createSessionInWorkspace.busy = false
3722
+ button.disabled = false
3723
+ }
3724
+ }
3725
+ const wbFs = { path: null, initial: null }
3726
+ function openWorkbenchModal() {
3727
+ $('modal-workbench').classList.remove('hidden')
3728
+ wbFs.path = null
3729
+ wbFs.initial = null
3730
+ wbFsLoad(null)
3731
+ setTimeout(() => $('wb-path-input').focus(), 50)
3732
+ }
3733
+ function closeWorkbenchModal() { wbFs.request = (wbFs.request || 0) + 1; $('modal-workbench').classList.add('hidden') }
3734
+ async function wbFsLoad(dir) {
3735
+ const connection = captureConnection(), request = wbFs.request = (wbFs.request || 0) + 1
3736
+ const valid = () => connection.valid() && request === wbFs.request
3737
+ const box = $('wb-fs-list')
3738
+ const target = dir ?? wbFs.path ?? ''
3739
+ box.innerHTML = `<div class="ds-empty">${esc(t('ds.loading'))}</div>`
3740
+ $('wb-fs-path').textContent = target ? '…' + target.slice(-40) : '~'
3741
+ try {
3742
+ const res = await fetch(fsApiUrl('/list', target ? { path: target } : {}), { headers: fsHeaders() })
3743
+ const data = await res.json().catch(() => ({}))
3744
+ if (!valid()) return
3745
+ if (!res.ok || !Array.isArray(data.entries)) throw new Error(data.error || ('HTTP ' + res.status))
3746
+ wbFs.path = data.path
3747
+ if (!wbFs.initial) wbFs.initial = data.path
3748
+ $('wb-fs-path').textContent = data.path
3749
+ const dirs = (data.entries || []).filter(e => e.type === 'dir')
3750
+ box.innerHTML = dirs.length ? dirs.map(e => {
3751
+ const p = wbJoin(data.path, e.name)
3752
+ return `<div class="ds-wb-fs-row" data-wb-dir="${esc(p)}"><span class="ds-fs-type">${desktopFsIconSvg(true)}</span><span class="ds-wb-fs-name">${esc(e.name)}</span><button type="button" class="ds-btn ds-wb-select" data-wb-select="${esc(p)}">${esc(t('wb.selectDir'))}</button></div>`
3753
+ }).join('') : `<div class="ds-empty">${esc(t('wb.empty'))}</div>`
3754
+ box.querySelectorAll('[data-wb-dir]').forEach(row => row.addEventListener('click', e => { if (!e.target.closest('[data-wb-select]')) wbFsLoad(row.dataset.wbDir) }))
3755
+ box.querySelectorAll('[data-wb-select]').forEach(button => button.addEventListener('click', () => bindWorkbench(button.dataset.wbSelect)))
3756
+ } catch (e) {
3757
+ if (!valid()) return
3758
+ $('wb-fs-path').textContent = target || '~'
3759
+ box.innerHTML = `<div class="ds-empty">${esc(e.message || t('ds.toastConnFailed'))}</div>`
3760
+ }
3761
+ }
3762
+ function wbFsUp() {
3763
+ if (wbFs.path && wbFs.initial && wbFs.path !== wbFs.initial) {
3764
+ const parent = wbFsParent(wbFs.path)
3765
+ if (parent) wbFsLoad(parent)
3766
+ }
3767
+ }
3768
+ async function bindWorkbench(rawPath) {
3769
+ const connection = captureConnection()
3770
+ const value = String(rawPath || '').trim()
3771
+ if (!value) return toast(t('wb.pathEmpty'), 'err')
3772
+ try {
3773
+ const wb = await wbGateway('POST', '/workbench/bind', { path: value })
3774
+ if (!connection.valid()) return
3775
+ state.wb = { bound: true, path: wb.path || value, title: wb.title || '', expanded: true, projects: null, open: null, apiMissing: false }
3776
+ const paths = [state.wb.path]
3777
+ try {
3778
+ const res = await fetch(fsApiUrl('/list', { path: state.wb.path }), { headers: fsHeaders() })
3779
+ const data = await res.json().catch(() => ({}))
3780
+ if (!connection.valid()) return
3781
+ for (const e of data.entries || []) if (e.type === 'dir') paths.push(wbJoin(state.wb.path, e.name))
3782
+ } catch {}
3783
+ for (const projectPath of paths) {
3784
+ if (!connection.valid()) return
3785
+ try { await rpc('workspace.create', { path: projectPath }) } catch {}
3786
+ }
3787
+ if (!connection.valid()) return
3788
+ closeWorkbenchModal()
3789
+ await refreshWorkbench({ silent: true })
3790
+ if (!connection.valid()) return
3791
+ await refreshSessions()
3792
+ if (!connection.valid()) return
3793
+ toast(t('wb.boundOk', { path: state.wb.path }), 'ok')
3794
+ } catch (e) {
3795
+ if (!connection.valid()) return
3796
+ if (e.message === 'AUTH') return toast(t('ds.toastAuth'), 'err')
3797
+ toast(t('wb.bindFailed', { msg: e.message }), 'err')
3798
+ }
3799
+ }
3800
+ async function unbindWorkbench() {
3801
+ if (!confirm(t('wb.unbindConfirm'))) return
3802
+ const connection = captureConnection()
3803
+ try {
3804
+ await wbGateway('POST', '/workbench/unbind')
3805
+ if (!connection.valid()) return
3806
+ state.wb = { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false }
3807
+ renderWorkbench()
3808
+ renderSessions()
3809
+ toast(t('wb.unboundOk'), 'ok')
3810
+ } catch (e) {
3811
+ if (!connection.valid()) return
3812
+ if (e.message === 'AUTH') return toast(t('ds.toastAuth'), 'err')
3813
+ toast(t('wb.unbindFailed', { msg: e.message }), 'err')
3814
+ }
3815
+ }
3816
+ let wbRefreshTimer = null
3817
+ function scheduleWorkbenchRefresh() {
3818
+ clearTimeout(wbRefreshTimer)
3819
+ wbRefreshTimer = setTimeout(() => refreshWorkbench({ silent: true }), 400)
3820
+ }
3821
+
3822
+ /* ---------------- 统计 ---------------- */
3823
+ function bucketTokens(b) { return (b.input || 0) + (b.cacheRead || 0) + (b.cacheWrite || 0) + (b.output || 0) }
3824
+ let statsDrawerOpened = false
3825
+ function toggleStatsDrawer() {
3826
+ const drawer = $('stats-drawer')
3827
+ if (!drawer) return
3828
+ const willOpen = drawer.classList.contains('hidden')
3829
+ drawer.classList.toggle('hidden')
3830
+ drawer.setAttribute('aria-hidden', willOpen ? 'false' : 'true')
3831
+ if (willOpen && !statsDrawerOpened) { statsDrawerOpened = true; loadStats() }
3832
+ }
3833
+ async function loadStats() {
3834
+ if (!state.token) {
3835
+ $('stats-cards').innerHTML = `<div class="ds-empty">${t('ds.statsGatewayDown')}</div>`
3836
+ $('stats-token-chart').innerHTML = ''
3837
+ $('stats-token-legend').innerHTML = ''
3838
+ return
3839
+ }
3840
+ try {
3841
+ const res = await fetch(apiUrl('/stats/summary?days=7'), { headers: { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() } })
3842
+ if (!res.ok) throw new Error('HTTP ' + res.status)
3843
+ const json = await res.json()
3844
+ renderStats(json.days || [])
3845
+ } catch {
3846
+ $('stats-cards').innerHTML = `<div class="ds-empty">${t('ds.statsGatewayDown')}</div>`
3847
+ $('stats-token-chart').innerHTML = ''
3848
+ $('stats-token-legend').innerHTML = ''
3849
+ }
3850
+ }
3851
+ function renderStats(days) {
3852
+ if (!days.length) {
3853
+ $('stats-cards').innerHTML = `<div class="ds-empty">${t('ds.statsEmpty')}</div>`
3854
+ $('stats-token-chart').innerHTML = ''
3855
+ $('stats-token-legend').innerHTML = ''
3856
+ return
3857
+ }
3858
+ const today = days[days.length - 1]
3859
+ const totalTokens = bucketTokens(today.total)
3860
+ const peakCost = today.peak.cost || 0
3861
+ const offCost = today.off.cost || 0
3862
+ const totalCost = peakCost + offCost
3863
+ const peakShare = totalCost > 0 ? Math.round(peakCost / totalCost * 100) : 0
3864
+ $('stats-cards').innerHTML = `
3865
+ <div class="ds-stat-card"><div class="v">${fmtTokens(totalTokens)}</div><div class="k">${t('ds.statsTodayTokens')}
3866
+ <div class="ds-bucket-grid">
3867
+ <div class="b"><span class="n">${t('ds.statsInput')}</span><span class="t">${fmtTokens(today.total.input)}</span></div>
3868
+ <div class="b"><span class="n">${t('ds.statsCacheRead')}</span><span class="t">${fmtTokens(today.total.cacheRead)}</span></div>
3869
+ <div class="b"><span class="n">${t('ds.statsCacheWrite')}</span><span class="t">${fmtTokens(today.total.cacheWrite)}</span></div>
3870
+ <div class="b"><span class="n">${t('ds.statsOutput')}</span><span class="t">${fmtTokens(today.total.output)}</span></div>
3871
+ </div></div></div>
3872
+ <div class="ds-stat-card"><div class="v">${fmtCost(totalCost)}</div><div class="k">${t('ds.statsTodayCost')}<br>${t('ds.statsPeak')} ${fmtCost(peakCost)} / ${t('ds.statsOff')} ${fmtCost(offCost)}</div></div>
3873
+ <div class="ds-stat-card"><div class="v">${peakShare}%</div><div class="k">${t('ds.statsPeakShare')}<br>${t('ds.statsDays', { n: days.length })}</div></div>`
3874
+ $('stats-legend').innerHTML = `<span class="sw peak"></span>${t('ds.statsPeak')} <span class="sw off"></span>${t('ds.statsOff')}`
3875
+ $('stats-token-legend').innerHTML = `<span class="sw token"></span>${t('ds.statsTokenTotal')}`
3876
+ $('stats-note').textContent = t('ds.statsNote')
3877
+ const maxCost = Math.max(...days.map(d => (d.total.cost || 0)), 0.0001)
3878
+ $('stats-chart').innerHTML = days.map(d => {
3879
+ const cost = d.total.cost || 0
3880
+ const peakH = cost > 0 ? Math.round((d.peak.cost || 0) / cost * 100) : 0
3881
+ const offH = cost > 0 ? Math.max(0, 100 - peakH) : 0
3882
+ const totalH = cost > 0 ? Math.max(3, Math.round(cost / maxCost * 100)) : 0
3883
+ const tip = `${d.date}\n${t('ds.statsPeak')} ${fmtCost(d.peak.cost)}\n${t('ds.statsOff')} ${fmtCost(d.off.cost)}`
3884
+ return `<div class="ds-stats-bar" data-tip="${esc(tip)}">
3885
+ <div class="bars" style="height:${totalH}%"><div class="seg peak" style="height:${peakH}%"></div><div class="seg off" style="height:${offH}%"></div></div>
3886
+ <div class="val">${cost > 0 ? fmtCost(cost) : ''}</div>
3887
+ <div class="lbl">${d.date.slice(5)}</div>
3888
+ </div>`
3889
+ }).join('')
3890
+ const maxTokens = Math.max(...days.map(d => bucketTokens(d.total)), 1)
3891
+ $('stats-token-chart').innerHTML = days.map(d => {
3892
+ const tokens = bucketTokens(d.total)
3893
+ const totalH = tokens > 0 ? Math.max(3, Math.round(tokens / maxTokens * 100)) : 0
3894
+ const tip = `${d.date}\n${t('ds.statsTokenTotal')} ${fmtTokens(tokens)}\n${t('ds.statsInput')} ${fmtTokens(d.total.input)} · ${t('ds.statsOutput')} ${fmtTokens(d.total.output)}`
3895
+ return `<div class="ds-stats-bar" data-tip="${esc(tip)}">
3896
+ <div class="bars token" style="height:${totalH}%"></div>
3897
+ <div class="val">${tokens > 0 ? fmtTokens(tokens) : ''}</div>
3898
+ <div class="lbl">${d.date.slice(5)}</div>
3899
+ </div>`
3900
+ }).join('')
3901
+ }
3902
+
3903
+ /* ---------------- 视图与连接状态 ---------------- */
3904
+ let overviewDetector = null
3905
+ let overviewPulse = null
3906
+ function setOverviewText(id,value){const node=$(id);if(overviewPulse)overviewPulse.text(node,value);else if(node)node.textContent=value}
3907
+ let overviewStarting = true
3908
+ function overviewChecks() {
3909
+ const confirmed=overviewDetector?.model.gateway===true,health=activeGatewayHealth()
3910
+ return {
3911
+ gateway: !!state.token && (!!state.server || /^https?:$/.test(location.protocol)) && confirmed,
3912
+ dsh: dshReachable() && confirmed,
3913
+ mux: !!state.streamsOk?.mux && confirmed && health?.events?.mux?.connected!==false,
3914
+ host: !!state.streamsOk?.host && confirmed && health?.events?.host?.connected!==false
3915
+ }
3916
+ }
3917
+ function repairMissingStreams() {
3918
+ if(!state.token||!navigator.onLine||state.selectingServer||overviewStarting)return
3919
+ if(state.streamMode==='poll'){tryRestoreWs();return}
3920
+ for(const [kind,handler,refresh] of [['mux',onMuxFrame,true],['host',onHostFrame,false]]) {
3921
+ const ws=streams[kind]
3922
+ if((!ws||ws.readyState===WebSocket.CLOSED)&&!streamMeta[kind].retryTimer)openStream(kind,handler,refresh)
3923
+ }
3924
+ }
3925
+ async function probeOverviewLinks(signal) {
3926
+ const connection=captureConnection(),base=String(connection.server||location.origin).replace(/\/+$/,'')
3927
+ let timer
3928
+ const controller=new AbortController(),cancel=()=>controller.abort()
3929
+ signal.addEventListener('abort',cancel,{once:true});if(signal.aborted)controller.abort()
3930
+ timer=setTimeout(cancel,6500)
3931
+ const healthRequest=fetch(base+'/health?probe=fresh&t='+Date.now(),{signal:controller.signal,cache:'no-store'}).then(async response=>{
3932
+ if(!response.ok)throw Error('health')
3933
+ const health=await response.json();if(health?.ok!==true)throw Error('health')
3934
+ return health
3935
+ }).catch(()=>null).finally(()=>{clearTimeout(timer);signal.removeEventListener('abort',cancel)})
3936
+ const [health,host]=await Promise.all([healthRequest,refreshHostDescriptionDesktop()])
3937
+ if(!connection.valid()||signal.aborted)throw Error('stale check')
3938
+ if(health){state.gatewayHealth[base]=health}
3939
+ else delete state.gatewayHealth[base]
3940
+ return {gateway:!!health}
3941
+ }
3942
+ function startOverviewDetection(force=false,identityChanged=false) {
3943
+ if(identityChanged)overviewDetector?.pause()
3944
+ if(!window.DshLinkCheck)return
3945
+ if(!overviewDetector)overviewDetector=new window.DshLinkCheck.LinkCheck({
3946
+ active:()=>document.visibilityState==='visible'&&!$('view-overview').classList.contains('hidden'),
3947
+ configured:()=>!!state.token&&(!!state.server||/^https?:$/.test(location.protocol)),online:()=>navigator.onLine,
3948
+ snapshot:overviewChecks,repair:repairMissingStreams,probe:probeOverviewLinks,changed:renderOverviewDesktop
3949
+ })
3950
+ overviewDetector.start(force)
3951
+ }
3952
+ window.addEventListener('online',()=>startOverviewDetection(true))
3953
+ window.addEventListener('offline',()=>startOverviewDetection(true))
3954
+ document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}})
3955
+
3956
+ function renderOverviewDesktop() {
3957
+ window.DshWorkflow?.update()
3958
+ const ring = $('ds-overview-pulse-ring')
3959
+ if (!ring) return
3960
+ const checks = overviewChecks()
3961
+ const detection=overviewDetector?.model,checking=detection?.phase==='checking'||(detection?.phase==='degraded'&&detection?.probing===true)
3962
+ const online = Object.values(checks).filter(Boolean).length
3963
+ $('ds-overview-refresh').disabled=detection?.probing===true
3964
+ const status = online === 4 ? 'Nominal' : online > 0 ? 'Degraded' : 'Offline'
3965
+ const pulseCard = document.querySelector('.ds-overview-pulse-card')
3966
+ if (pulseCard) {
3967
+ if(!overviewPulse&&window.DshLinkCheck?.PulseVisual)overviewPulse=new window.DshLinkCheck.PulseVisual({card:pulseCard,active:()=>document.visibilityState==='visible'&&!$('view-overview').classList.contains('hidden')})
3968
+ overviewPulse?.setChecking(checking)
3969
+ overviewPulse?.setLinks(checks)
3970
+ pulseCard.classList.remove('status-nominal', 'status-degraded', 'status-offline')
3971
+ pulseCard.classList.toggle('status-checking',checking)
3972
+ pulseCard.setAttribute('aria-busy',String(checking))
3973
+ pulseCard.classList.add('status-' + status.toLowerCase())
3974
+ }
3975
+ setOverviewText('ds-overview-health',checking ? t('ds.checking') : online === 4 ? t('ds.live') : online ? `${online}/4` : t('ds.offlineCore'))
3976
+ setOverviewText('ds-overview-health-caption',checking ? `${online}/4` : online === 4 ? t('ds.allLinked') : online ? t('ds.confirmedShort') : t('ds.offlineShort'))
3977
+ setOverviewText('ds-overview-status',checking ? t('ds.checking') : t(`ds.system${status}`))
3978
+ setOverviewText('ds-overview-status-desc',checking ? t('ds.autoChecking',{n:online}) : detection?.phase==='degraded' ? t('ds.autoRetry',{n:online}) : t('ds.components',{n:online}))
3979
+ for (const [name, ok] of Object.entries(checks)) {
3980
+ const item = document.querySelector(`[data-ds-overview-link="${name}"]`)
3981
+ if (!item) continue
3982
+ item.classList.toggle('ok', ok)
3983
+ item.classList.toggle('off', !ok&&!checking)
3984
+ item.classList.toggle('pending',!ok&&checking)
3985
+ const value = item.querySelector('b')
3986
+ if (value) setOverviewText(value.id || (value.id=`ds-overview-link-${name}`), ok ? t('ds.online') : checking ? t('ds.checkingShort') : t('ds.offlineShort'))
3987
+ }
3988
+
3989
+ const pending = [
3990
+ ...state.approvals.map(a => ({ kind: 'approval', item: a })),
3991
+ ...state.questions.map(q => ({ kind: 'question', item: q }))
3992
+ ]
3993
+ $('ds-overview-attention-count').textContent = pending.length ? t('ds.pendingCount', { n: pending.length }) : '—'
3994
+ $('ds-overview-attention-list').innerHTML = pending.length ? pending.map(({ kind, item }) => {
3995
+ const title = sessionLabelOf(state.byId.get(item.sessionId))
3996
+ if (kind === 'approval') return `<div class="ds-overview-attention-item" data-ds-overview-approval="${esc(item.approvalId)}">
3997
+ <span class="ds-overview-mark">⌁</span><span class="ds-overview-copy"><span class="ds-overview-item-title">${esc(item.toolName || t('ds.toolDefault'))}</span><span class="ds-overview-item-desc">${esc(desktopApprovalDetail(item))} · ${esc(title)}</span></span>
3998
+ <span class="ds-overview-actions"><button class="ds-btn allow" data-ds-overview-approve="1">${t('ds.allow')}</button><button class="ds-btn reject" data-ds-overview-approve="0">${t('ds.reject')}</button></span>
3999
+ </div>`
4000
+ return `<button type="button" class="ds-overview-attention-item question" data-ds-overview-question="${esc(item.rpcId)}">
4001
+ <span class="ds-overview-mark">?</span><span class="ds-overview-copy"><span class="ds-overview-item-title">${esc(item.questions?.[0]?.question || t('ds.questionNotify'))}</span><span class="ds-overview-item-desc">${esc(title)}</span></span><span class="ds-overview-arrow">›</span>
4002
+ </button>`
4003
+ }).join('') : `<div class="ds-overview-empty">${t('ds.nothingPending')}</div>`
4004
+ $('ds-overview-attention-list').querySelectorAll('[data-ds-overview-approve]').forEach(btn => btn.addEventListener('click', () => approveApproval(btn.closest('[data-ds-overview-approval]')?.dataset.dsOverviewApproval || '', btn.dataset.dsOverviewApprove === '1')))
4005
+ $('ds-overview-attention-list').querySelectorAll('[data-ds-overview-question]').forEach(btn => btn.addEventListener('click', () => openQuestionModal(state.questions.find(q => q.rpcId === btn.dataset.dsOverviewQuestion))))
4006
+ renderApprovalRecordsDesktop()
4007
+
4008
+ const topSessions = topLevelSessions()
4009
+ const running = topSessions.filter(s => s.running).length
4010
+ const sessions = topSessions.sort((a, b) => Number(b.running) - Number(a.running) || (sessionSortTime(b) - sessionSortTime(a))).slice(0, 6)
4011
+ const primary = $('ds-overview-primary-action')
4012
+ if (primary) {
4013
+ let action = 'new'
4014
+ let label = t('ds.action.newSession')
4015
+ let sessionId = ''
4016
+ if (!state.token) {
4017
+ action = 'settings'
4018
+ label = t('ds.action.connect')
4019
+ } else if (online > 0 && online < 4) {
4020
+ action = 'refresh'
4021
+ label = t('ds.action.refresh')
4022
+ } else if (pending.length) {
4023
+ action = 'attention'
4024
+ label = t('ds.action.attention')
4025
+ } else if (sessions.length) {
4026
+ action = 'session'
4027
+ sessionId = sessions[0].sessionId
4028
+ label = t('ds.action.openSession')
4029
+ }
4030
+ primary.textContent = label
4031
+ primary.dataset.dsOverviewAction = action
4032
+ primary.dataset.dsOverviewSession = sessionId
4033
+ }
4034
+ $('ds-overview-dsh-version').textContent = state.hostInfo?.version || '—'
4035
+ $('ds-overview-gateway-version').textContent = checks.gateway ? t('ds.online') : t('ds.offlineShort')
4036
+ $('ds-overview-active-sessions').textContent = String(running)
4037
+ $('ds-overview-connection-mode').textContent = state.token ? t(state.streamMode === 'poll' ? 'ds.poll' : 'ds.liveWs') : '—'
4038
+ $('ds-overview-active-count').textContent = running ? t('ds.activeCount', { n: running }) : ''
4039
+ $('ds-overview-session-list').innerHTML = sessions.length ? sessions.map(s => `<button type="button" class="ds-overview-session-item ${s.running ? 'running' : ''}" data-ds-overview-session="${esc(s.sessionId)}">
4040
+ <span class="ds-overview-mark">${s.running ? '●' : '○'}</span><span class="ds-overview-copy"><span class="ds-overview-item-title">${esc(sessionLabelOf(s))}</span><span class="ds-overview-item-desc">${s.running ? esc(t('ds.running')) + ' · ' : ''}${esc(fmtTime(sessionSortTime(s)))}</span></span><span class="ds-overview-arrow">›</span>
4041
+ </button>`).join('') : `<div class="ds-overview-empty">${t('ds.noSessions')}</div>`
4042
+ $('ds-overview-session-list').querySelectorAll('[data-ds-overview-session]').forEach(btn => btn.addEventListener('click', () => openSession(btn.dataset.dsOverviewSession)))
4043
+ }
4044
+
4045
+ const narrowSidebarQuery = window.matchMedia('(max-width: 1023px)')
4046
+ function setMobileSidebar(open) {
4047
+ const sidebar = $('ds-sidebar')
4048
+ const backdrop = $('ds-sidebar-backdrop')
4049
+ const trigger = $('btn-mobile-nav')
4050
+ if (!sidebar || !backdrop || !trigger) return
4051
+ const visible = !!open && narrowSidebarQuery.matches
4052
+ sidebar.classList.toggle('mobile-open', visible)
4053
+ backdrop.classList.toggle('hidden', !visible)
4054
+ trigger.setAttribute('aria-expanded', String(visible))
4055
+ sidebar.inert = narrowSidebarQuery.matches && !visible
4056
+ $('ds-app')?.classList.toggle('mobile-nav-open', visible)
4057
+ }
4058
+
4059
+ function openDesktopPlugins(route = 'manage') {
4060
+ const connection=captureConnection()
4061
+ if(!connection.token){$('desktop-plugin-page').textContent=t('ds.toastAuth');return}
4062
+ window.DshExtensions.mount({connection,getWorkspaces: () => state.workspaces || [],
4063
+ getWorkspaceId: () => (state.workspaces || []).find(w => (w.sessionIds || []).includes(state.current))?.workspaceId || '',
4064
+ openTeamCaptain: async id => { if (!connection.valid()) return; await openSession(id) },
4065
+ openTaskSession: async (id, workspaceId) => {
4066
+ if (!connection.valid() || state.view !== 'view-plugins') return
4067
+ if (!(state.workspaces || []).some(row => row.workspaceId === workspaceId)) throw Error('unavailable')
4068
+ await openSession(id)
4069
+ },
4070
+ openTeamMember: async (id, parentId) => {
4071
+ const selected = state.current
4072
+ const catalog = await loadSessionSubagents(parentId)
4073
+ if (!connection.valid() || state.view !== 'view-plugins' || state.current !== selected) return
4074
+ const entry = catalog?.entries?.find(row => row.id === id)
4075
+ if (!entry || entry.kind === 'diagnostic') throw Error('unavailable')
4076
+ rememberSubagent(entry, parentId)
4077
+ await openSession(id)
4078
+ },
4079
+ 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)
4080
+ }
4081
+
4082
+ function showView(id, pluginRoute = 'manage') {
4083
+ window.DshExtensions?.closeShortcuts()
4084
+ if (id !== 'view-chat') window.DshSubagents?.close()
4085
+ document.body?.classList.toggle('viewing-subagent', id === 'view-chat' && state.byId.get(state.current)?.origin === 'subagent')
4086
+ window.DshWorkflow?.close()
4087
+ if (window.DshWorkflow?.isMounted() && id === 'view-overview') id = 'view-sessions'
4088
+ if (id !== 'view-chat') conversationView?.pause()
4089
+ if (state.view === 'view-chat' && id !== 'view-chat' && state.current) void archiveEmptySessionOnLeave(state.current)
4090
+ state.view = id
4091
+ window.DshFileInbox?.render()
4092
+ window.DshSessionDeck?.refresh()
4093
+ document.body?.classList.toggle('workflow-at-start', !!window.DshWorkflow?.isMounted() && id === 'view-sessions')
4094
+ for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
4095
+ if (id === 'view-chat') conversationView?.resume()
4096
+ document.querySelectorAll('.ds-nav-item').forEach(b => b.classList.toggle('active', b.dataset.view === id))
4097
+ if (narrowSidebarQuery.matches) setMobileSidebar(false)
4098
+ window.DshMotion?.view($(id))
4099
+ const titles = { 'view-overview': 'ds.overview', 'view-sessions': 'ds.sessions', 'view-chat': 'ds.sessions', 'view-files': 'ds.files', 'view-settings': 'ds.settings', 'view-plugins': 'ds.plugins' }
4100
+ if (id === 'view-chat') { const s = state.byId.get(state.current); $('ds-title').textContent = s ? titleOf(s) : t('ds.sessions') }
4101
+ else $('ds-title').textContent = t(titles[id])
4102
+ if (id === 'view-overview') {startOverviewDetection(true);renderOverviewDesktop()}
4103
+ else {overviewDetector?.pause();overviewPulse?.pause()}
4104
+ if (id === 'view-files' && !state.fs.loaded) loadFs(null, true)
4105
+ if (id === 'view-settings') showSettingsHome()
4106
+ if (id === 'view-plugins') openDesktopPlugins(pluginRoute)
4107
+ else window.DshExtensions?.close()
4108
+ updateSessionActions()
4109
+ }
4110
+
4111
+ function updateSessionActions() {
4112
+ const active = state.view === 'view-chat' && !!state.current
4113
+ $('btn-subagents')?.classList.toggle('hidden', !active)
4114
+ $('btn-rename-session')?.classList.toggle('hidden', !active)
4115
+ $('btn-archive-session')?.classList.toggle('hidden', !active || state.archivedIds.includes(state.current))
4116
+ $('ds-session-status')?.classList.toggle('hidden', !active || !recoveryLabel())
4117
+ if (!active) $('ds-workspace')?.classList.add('hidden')
4118
+ if (active) {
4119
+ const s = state.byId.get(state.current)
4120
+ $('ds-title').textContent = s ? titleOf(s) : t('ds.sessions')
4121
+ const workspace = s?.cwd || ''
4122
+ $('ds-workspace').textContent = '📁 ' + (workspace.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || t('ds.noWorkspace')) + ' ›'
4123
+ $('ds-workspace').title = workspace
4124
+ $('ds-workspace').classList.remove('hidden')
4125
+ $('ds-session-status').textContent = recoveryLabel()
4126
+ }
4127
+ const running = !!state.byId.get(state.current)?.running || (state.queues[state.current] || []).some(i => i.placement !== 'context')
4128
+ $('btn-cancel')?.classList.toggle('hidden', !active || !running)
4129
+ }
4130
+
4131
+ const SETTINGS_GROUPS = ['general', 'servers', 'theme', 'about']
4132
+ function showSettingsHome() {
4133
+ const home = $('settings-home')
4134
+ if (!home) return
4135
+ home.classList.remove('hidden')
4136
+ for (const name of SETTINGS_GROUPS) $('settings-page-' + name)?.classList.add('hidden')
4137
+ }
4138
+ function showSettingsPage(name) {
4139
+ const home = $('settings-home')
4140
+ if (!home || !SETTINGS_GROUPS.includes(name)) return
4141
+ home.classList.add('hidden')
4142
+ for (const g of SETTINGS_GROUPS) $('settings-page-' + g)?.classList.toggle('hidden', g !== name)
4143
+ if (name === 'general') renderPresetSummary()
4144
+ }
4145
+ function updateConn() {
4146
+ overviewDetector?.observe()
4147
+ const el = $('conn-badge')
4148
+ // 双实时通道可能按任意顺序打开,连接刷新必须同时刷新系统总览。
4149
+ renderOverviewDesktop()
4150
+ const cur = currentServerEntry()
4151
+ const group = cur ? cur.group : state.activeGroup
4152
+ const label = cur ? (cur.note || cur.url) : (state.server || t('ds.origin'))
4153
+ const serverText = t('ds.currentServer', { group, url: label })
4154
+ if (!navigator.onLine) {
4155
+ el.textContent = t('ds.connOffline')
4156
+ el.className = 'ds-conn off'
4157
+ el.title = serverText
4158
+ $('server-badge').textContent = serverText
4159
+ return
4160
+ }
4161
+ if (state.streamMode === 'poll') {
4162
+ el.textContent = '●'
4163
+ el.className = 'ds-conn off'
4164
+ el.title = t('ds.connPollTitle')
4165
+ $('server-badge').textContent = serverText
4166
+ return
4167
+ }
4168
+ const any = Object.values(state.streamsOk).some(Boolean)
4169
+ const all = state.streamsOk.mux && state.streamsOk.host
4170
+ if (!all && reconnectInfo) {
4171
+ const remain = Math.max(0, Math.ceil((reconnectInfo.at - Date.now()) / 1000))
4172
+ el.textContent = remain > 0 ? t('ds.connReconnectIn', { n: remain }) : t('ds.connReconnecting')
4173
+ el.className = 'ds-conn ing'
4174
+ el.title = t('ds.connReconnecting') + ' · ' + serverText
4175
+ $('server-badge').textContent = serverText
4176
+ return
4177
+ }
4178
+ if (!all && state.errCount > 0 && !any) {
4179
+ el.textContent = t('ds.connFailed')
4180
+ el.className = 'ds-conn off'
4181
+ el.title = serverText
4182
+ $('server-badge').textContent = serverText
4183
+ return
4184
+ }
4185
+ el.textContent = '●'
4186
+ el.className = 'ds-conn ' + (all ? 'on' : any ? 'ing' : '')
4187
+ el.title = all ? t('ds.connOn') : any ? t('ds.connIng') : t('ds.connOff')
4188
+ $('server-badge').textContent = serverText
4189
+ }
4190
+
4191
+ /* ---------------- 初始化 ---------------- */
4192
+
4193
+ function bindSessionDialogs() {
4194
+ const actions=$('session-actions'), info=$('session-info');
4195
+ $('btn-session-more').addEventListener('click',()=>actions.showModal());
4196
+ actions.addEventListener('click',e=>{if(e.target===actions)actions.close();else if(e.target.closest('button'))actions.close()},true);
4197
+ const openInfo=()=>{const s=state.byId.get(state.current);if(!s)return; $('session-info-name').textContent=titleOf(s);$('session-info-path').textContent=s.cwd||t('ds.noWorkspace');$('session-info-id').textContent=s.sessionId;$('btn-copy-session-workspace').disabled=!s.cwd;info.showModal()};
4198
+ $('ds-title').addEventListener('click',openInfo);
4199
+ $('ds-workspace').addEventListener('click',openInfo);
4200
+ $('btn-session-info').addEventListener('click',openInfo);
4201
+ info.addEventListener('click',e=>{if(e.target===info||e.target.closest('[data-session-dialog-close]'))info.close()});
4202
+ $('btn-copy-session-workspace').addEventListener('click',async()=>{const value=state.byId.get(state.current)?.cwd;if(value&&await copyText(value))toast(t('ds.copied'),'ok')});
4203
+ }
4204
+
4205
+ function bindUi() {
4206
+ $('conn-badge').addEventListener('click', () => { toast(t('ds.connRefresh')); openStreams(); void refreshSessions(); startOverviewDetection(true) })
4207
+ window.DshExtensions?.bindShortcuts({ trigger: $('btn-plugin-shortcuts'), menu: $('plugin-shortcuts-menu'),
4208
+ config: () => optionalPluginConfig(), connected: () => !!state.token, hasSession: () => !!state.current,
4209
+ beforeOpen: () => setMobileSidebar(false),
4210
+ open: route => { if (route === 'context') void openInsights('context', true); else showView('view-plugins', route) } })
4211
+ bindSessionDialogs()
4212
+ getConversationView()
4213
+ $('btn-history-latest').addEventListener('click',()=>{getConversationView().latest();if(state.history.tailEvicted)void loadHistory(true)})
4214
+ $('btn-new-session').addEventListener('click', openNewSessionModal)
4215
+ $('btn-new-workspace').addEventListener('click', openWorkspaceModal)
4216
+ $('session-sort')?.addEventListener('change', (e) => {
4217
+ state.sessionSort = e.target.value === 'workspace' ? 'workspace' : 'time'
4218
+ LS.set('sessionSort', state.sessionSort)
4219
+ renderSessions()
4220
+ })
4221
+ $('btn-mobile-nav').addEventListener('click', () => setMobileSidebar(!$('ds-sidebar').classList.contains('mobile-open')))
4222
+ $('ds-sidebar-backdrop').addEventListener('click', () => setMobileSidebar(false))
4223
+ narrowSidebarQuery.addEventListener?.('change', () => setMobileSidebar(false))
4224
+ document.addEventListener('keydown', (event) => {
4225
+ if (event.key === 'Escape' && $('ds-sidebar').classList.contains('mobile-open')) {
4226
+ setMobileSidebar(false)
4227
+ $('btn-mobile-nav').focus()
4228
+ }
4229
+ })
4230
+ document.querySelectorAll('.ds-nav-item').forEach(b => b.addEventListener('click', () => showView(b.dataset.view)))
4231
+ $('ds-overview-refresh').addEventListener('click',()=>{startOverviewDetection(true);if(state.token)void refreshSessions()})
4232
+ $('ds-overview-primary-action').addEventListener('click', () => {
4233
+ const button = $('ds-overview-primary-action')
4234
+ const action = button.dataset.dsOverviewAction
4235
+ if (action === 'session' && button.dataset.dsOverviewSession) return openSession(button.dataset.dsOverviewSession)
4236
+ if (action === 'new') return $('btn-new-session').click()
4237
+ if (action === 'settings') return showView('view-settings')
4238
+ if (action === 'refresh') return $('ds-overview-refresh').click()
4239
+ const first = document.querySelector('.ds-overview-attention-item')
4240
+ if (first) {
4241
+ first.scrollIntoView({ behavior: 'smooth', block: 'center' })
4242
+ if (first.matches('button')) first.focus({ preventScroll: true })
4243
+ }
4244
+ })
4245
+ $('session-list').addEventListener('click', (e) => {
4246
+ if (e.target.closest('[data-archived-toggle]')) {
4247
+ LS.set('dsShowArchivedV1', LS.get('dsShowArchivedV1', '0') === '1' ? '0' : '1')
4248
+ renderSessions()
4249
+ return
4250
+ }
4251
+ const item = e.target.closest('[data-id]')
4252
+ if (item) openSession(item.dataset.id)
4253
+ })
4254
+ $('btn-wb-bind').addEventListener('click', openWorkbenchModal)
4255
+ $('btn-wb-bind-manual').addEventListener('click', () => bindWorkbench($('wb-path-input').value))
4256
+ $('wb-path-input').addEventListener('keydown', e => {
4257
+ if (e.key === 'Enter' && !e.isComposing) { e.preventDefault(); bindWorkbench($('wb-path-input').value) }
4258
+ })
4259
+ $('wb-fs-up').addEventListener('click', wbFsUp)
4260
+ $('wb-fs-home').addEventListener('click', () => wbFsLoad(wbFs.initial || null))
4261
+ $('btn-wb-modal-close').addEventListener('click', closeWorkbenchModal)
4262
+ $('modal-workbench').addEventListener('click', e => { if (e.target === $('modal-workbench')) closeWorkbenchModal() })
4263
+ $('wb-head').addEventListener('click', () => {
4264
+ state.wb.expanded = !state.wb.expanded
4265
+ if (state.wb.expanded && !state.wb.projects) refreshWorkbench({ silent: false })
4266
+ else renderWorkbench()
4267
+ })
4268
+ $('btn-wb-path').addEventListener('click', () => { if (state.wb.path) toast(t('wb.boundPath', { path: state.wb.path }), 'ok') })
4269
+ $('btn-wb-unbind').addEventListener('click', unbindWorkbench)
4270
+ $('btn-send').addEventListener('click', sendMessage)
4271
+ $('btn-cancel').addEventListener('click', cancelSession)
4272
+ $('btn-rename-session').addEventListener('click', () => renameSession())
4273
+ $('btn-archive-session').addEventListener('click', archiveCurrentSession)
4274
+ $('rename-cancel').addEventListener('click', closeRenameSession)
4275
+ $('rename-confirm').addEventListener('click', confirmRenameSession)
4276
+ $('rename-session-input').addEventListener('keydown', e => { if (e.key === 'Enter' && !e.isComposing) confirmRenameSession() })
4277
+ $('modal-rename').addEventListener('click', e => { if (e.target === $('modal-rename')) closeRenameSession() })
4278
+ $('composer').addEventListener('keydown', (e) => {
4279
+ if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); sendMessage() }
4280
+ })
4281
+ renderPresetMenuDesktop()
4282
+ renderPresetSummary()
4283
+ $('btn-cmd').addEventListener('click', (e) => { e.stopPropagation(); toggleCmdMenuDesktop() })
4284
+ $('cmd-menu').addEventListener('click', (e) => {
4285
+ const item = e.target.closest('[data-ds-cmd]')
4286
+ if (item) {
4287
+ const input = $('composer')
4288
+ input.value = item.dataset.dsCmd + ' '
4289
+ input.focus()
4290
+ $('cmd-menu').classList.add('hidden')
4291
+ }
4292
+ })
4293
+ $('btn-preset').addEventListener('click', (e) => { e.stopPropagation(); togglePresetMenuDesktop() })
4294
+ $('preset-menu').addEventListener('click', (e) => {
4295
+ const item = e.target.closest('[data-ds-preset]')
4296
+ if (item) {
4297
+ const found = readPresets().find(x => x.id === item.dataset.dsPreset)
4298
+ if (found) {
4299
+ const input = $('composer')
4300
+ input.value = found.text
4301
+ input.focus()
4302
+ }
4303
+ $('preset-menu').classList.add('hidden')
4304
+ }
4305
+ })
4306
+ $('btn-model').addEventListener('click', (e) => { e.stopPropagation(); toggleModelMenuDesktop() })
4307
+ $('model-menu').addEventListener('click', (e) => {
4308
+ if (e.target.closest('[data-model]') || e.target.closest('[data-effort]')) e.stopPropagation()
4309
+ })
4310
+ document.addEventListener('click', (e) => {
4311
+ if (!e.target.closest('#preset-menu') && !e.target.closest('#btn-preset')) $('preset-menu')?.classList.add('hidden')
4312
+ if (!e.target.closest('#cmd-menu') && !e.target.closest('#btn-cmd')) $('cmd-menu')?.classList.add('hidden')
4313
+ if (!e.target.closest('#model-menu') && !e.target.closest('#btn-model')) $('model-menu')?.classList.add('hidden')
4314
+ })
4315
+ $('btn-stats-top').addEventListener('click', toggleStatsDrawer)
4316
+ for (const id of ['history', 'question-body']) window.DshChatFiles?.bind($(id), () => {
4317
+ const c=captureConnection(),sessionId=id==='history'?state.current:state.questionModal?.sessionId
4318
+ return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:false,headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,preview:(path,name)=>window.DshWorkflow?.preview({...c,headers:{authorization:'Bearer '+c.token}},path,name),
4319
+ valid:()=>c.valid()&&sessionId===(id==='history'?state.current:state.questionModal?.sessionId) }
4320
+ })
4321
+ $('btn-insights').addEventListener('click', () => openInsights())
4322
+ $('stats-drawer-close').addEventListener('click', toggleStatsDrawer)
4323
+ // 赞赏支持
4324
+ $('btn-donate-about').addEventListener('click', openDonateModal)
4325
+ $('btn-donate-close').addEventListener('click', () => $('modal-donate').classList.add('hidden'))
4326
+ // 更新内容弹窗
4327
+ $('notes-close').addEventListener('click', closeNotesModal)
4328
+ $('notes-prev').addEventListener('click', () => scrollNotes(-1))
4329
+ $('notes-next').addEventListener('click', () => scrollNotes(1))
4330
+ $('notes-pages').addEventListener('scroll', updateNotesPage)
4331
+ $('workspace-cancel').addEventListener('click', closeWorkspaceModal)
4332
+ $('workspace-create').addEventListener('click', createWorkspace)
4333
+ $('workspace-name').addEventListener('keydown', (e) => { if (e.key === 'Enter') createWorkspace() })
4334
+ $('modal-workspace').addEventListener('click', (e) => { if (e.target === $('modal-workspace')) closeWorkspaceModal() })
4335
+ $('new-session-workspace').addEventListener('change', () => renderNewSessionWorkspace())
4336
+ $('new-session-cancel').addEventListener('click', closeNewSessionModal)
4337
+ $('new-session-create').addEventListener('click', createSessionInWorkspace)
4338
+ $('modal-new-session').addEventListener('click', (e) => { if (e.target === $('modal-new-session')) closeNewSessionModal() })
4339
+ $('modal-notes').addEventListener('click', (e) => { if (e.target === $('modal-notes')) closeNotesModal() })
4340
+ // 反馈
4341
+ $('fb-cancel').addEventListener('click', closeFeedbackModal)
4342
+ $('fb-submit').addEventListener('click', submitFeedback)
4343
+ $('fb-msg').addEventListener('input', updateFeedbackLength)
4344
+ $('fb-copy-draft').addEventListener('click', async () => { const ok = await copyText($('fb-msg').value); toast(I18N.lang === 'en' ? (ok ? 'Copied' : 'Copy failed') : (ok ? '已复制全文' : '复制失败,请重试'), ok ? 'ok' : 'err') })
4345
+ $('fb-include-diagnostics').addEventListener('change',()=>{void loadCrashPreview()})
4346
+ $('fb-include-crashes').addEventListener('change',()=>{void loadCrashPreview()})
4347
+ document.querySelectorAll('#fb-chips .ds-fb-chip').forEach(btn =>
4348
+ btn.addEventListener('click', () => {
4349
+ document.querySelectorAll('#fb-chips .ds-fb-chip').forEach(b => b.classList.toggle('current', b === btn))
4350
+ }))
4351
+ // 统计柱状图悬停提示: 自定义 tooltip, 限制在视口内, 避免原生 title 溢出抽屉
4352
+ $('stats-chart').addEventListener('mouseover', (e) => {
4353
+ const bar = e.target.closest('.ds-stats-bar')
4354
+ if (bar && bar.dataset.tip) showTip(bar.dataset.tip, bar.getBoundingClientRect())
4355
+ })
4356
+ $('stats-chart').addEventListener('mouseleave', hideTip)
4357
+ $('stats-token-chart').addEventListener('mouseover', (e) => {
4358
+ const bar = e.target.closest('.ds-stats-bar')
4359
+ if (bar && bar.dataset.tip) showTip(bar.dataset.tip, bar.getBoundingClientRect())
4360
+ })
4361
+ $('stats-token-chart').addEventListener('mouseleave', hideTip)
4362
+
4363
+ $('view-settings').addEventListener('click', (e) => {
4364
+ const group = e.target.closest('[data-settings-group]')
4365
+ if (group) { showSettingsPage(group.dataset.settingsGroup); return }
4366
+ if (e.target.closest('[data-settings-back]')) { showSettingsHome(); return }
4367
+ })
4368
+ $('btn-manage-presets').addEventListener('click', openPresetModal)
4369
+ $('btn-preset-add').addEventListener('click', addPreset)
4370
+ $('btn-presets-close').addEventListener('click', closePresetModal)
4371
+ $('modal-presets').addEventListener('click', (e) => { if (e.target === $('modal-presets')) closePresetModal() })
4372
+ $('btn-server-speed').addEventListener('click', () => selectFastestServer({ silent: false }))
4373
+ $('btn-server-add').addEventListener('click', addServer)
4374
+ $('btn-group-add').addEventListener('click', addGroup)
4375
+ $('group-select-btn').addEventListener('click', (e) => { e.stopPropagation(); toggleGroupMenu() })
4376
+ $('ds-group-drawer-trigger').addEventListener('click', () => { desktopGroupDrawerOpen() ? closeDesktopGroupDrawer() : openDesktopGroupDrawer() })
4377
+ $('ds-group-drawer-close').addEventListener('click', () => closeDesktopGroupDrawer())
4378
+ $('ds-group-drawer-backdrop').addEventListener('click', () => closeDesktopGroupDrawer())
4379
+ $('ds-group-drawer-list').addEventListener('click', (e) => {
4380
+ const option = e.target.closest('[data-ds-quick-group]')
4381
+ if (!option) return
4382
+ const group = option.dataset.dsQuickGroup
4383
+ closeDesktopGroupDrawer({ restoreFocus: false })
4384
+ if (group !== state.activeGroup) switchGroup(group)
4385
+ })
4386
+ $('ds-group-drawer-manage').addEventListener('click', () => {
4387
+ closeDesktopGroupDrawer({ restoreFocus: false })
4388
+ showView('view-settings')
4389
+ showSettingsPage('servers')
4390
+ })
4391
+ document.addEventListener('keydown', keepDesktopGroupDrawerFocus)
4392
+ document.addEventListener('click', (e) => { if (!e.target.closest('#group-select')) closeGroupMenu() })
4393
+ $('server-input').addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.isComposing) { e.preventDefault(); addServer() } })
4394
+
4395
+ $('btn-copy-token').addEventListener('click', async () => {
4396
+ try { await navigator.clipboard.writeText(state.token); toast(t('ds.toastCopied'), 'ok') }
4397
+ catch { toast(t('ds.toastOpFailed'), 'err') }
4398
+ })
4399
+ $('desktop-token-save').addEventListener('click', () => void saveAccessTokenDesktop())
4400
+ $('desktop-token-input').addEventListener('keydown', event => {
4401
+ if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); void saveAccessTokenDesktop() }
4402
+ })
4403
+ $('btn-theme').addEventListener('click', () => {
4404
+ window.DSHTheme.openPicker({
4405
+ themes: THEME_META, current: themeGet(), label: id => t('ds.theme.' + id),
4406
+ lang: I18N.lang, onSelect: themeSet
4407
+ })
4408
+ })
4409
+ $('btn-lang').addEventListener('click', () => {
4410
+ I18N.setLang(I18N.lang === 'zh' ? 'en' : 'zh')
4411
+ $('btn-lang').textContent = I18N.lang === 'zh' ? 'EN' : '中文'
4412
+ renderServers(); renderSessions(); renderNotifStack(); renderOverviewDesktop(); updateConn(); themeApply(); void refreshInsightEntry()
4413
+ })
4414
+ $('fs-up').addEventListener('click', fsUp)
4415
+ $('fs-root').addEventListener('change', (event) => {
4416
+ const index = Math.min(Number(event.target.value) || 0, Math.max(0, state.fs.roots.length - 1))
4417
+ state.fs.rootIndex = index
4418
+ state.fs.initial = null
4419
+ loadFs(state.fs.roots[index] || null, true)
4420
+ })
4421
+ $('fs-new-workspace').addEventListener('click', openWorkspaceModal)
4422
+ $('fs-refresh').addEventListener('click', () => loadFs(state.fs.path || null))
4423
+ $('btn-question-submit').addEventListener('click', submitQuestion)
4424
+ $('btn-question-cancel').addEventListener('click', () => { $('modal-question').classList.add('hidden'); toast(t('ds.ignored'), 'ok') })
4425
+ }
4426
+
4427
+ async function saveAccessTokenDesktop() {
4428
+ const value = $('desktop-token-input').value.trim()
4429
+ if (!value) return
4430
+ state.token = value; LS.set('token', value)
4431
+ const current = state.servers.find(s => s.id === state.groupActive[state.activeGroup]) || state.servers.find(s => s.url === (state.server || location.origin))
4432
+ if (current) current.token = value
4433
+ saveServers(); $('desktop-token-input').value = ''
4434
+ $('token-desc').textContent = '● ' + value.slice(0, 12) + '…'
4435
+ showView('view-overview'); openStreams()
4436
+ await Promise.all([refreshSessions(), refreshHostDescriptionDesktop()])
4437
+ void refreshWorkbench({ silent: true })
4438
+ }
4439
+
4440
+ async function start() {
4441
+ const urlToken = new URLSearchParams(location.search).get('token')?.trim() || ''
4442
+ if (urlToken) {
4443
+ state.token = urlToken
4444
+ LS.set('token', urlToken)
4445
+ history.replaceState(null, '', location.pathname)
4446
+ }
4447
+ loadServers()
4448
+ doctorSessionHandoff = window.DshDoctorEntry?.restoreSessionConnection?.({state,newId:newServerId,persist:()=>{LS.set('token',state.token);saveServers()}}) === true
4449
+ renderServers()
4450
+ showView(window.DshWorkflow?.isMounted() ? 'view-sessions' : 'view-overview')
4451
+ if (urlToken) {
4452
+ state.token = urlToken
4453
+ const currentId = state.groupActive[state.activeGroup]
4454
+ const current = state.servers.find(s => s.id === currentId) || state.servers.find(s => s.url === state.server)
4455
+ if (current) current.token = urlToken
4456
+ LS.set('token', urlToken)
4457
+ saveServers()
4458
+ }
4459
+ $('token-desc').textContent = state.token ? '● ' + state.token.slice(0, 12) + '…' : t('ds.toastAuth')
4460
+ bindUi()
4461
+ window.DshImagePreview?.configure?.({ resolvePath: chatImageRequest, resolveAttachment: chatImageAttachment, capture: captureChatImage })
4462
+ if (!state.token) { showView('view-settings'); $('desktop-token-input').focus() }
4463
+ renderWorkbench()
4464
+ updateConn()
4465
+ checkNotesOnStart()
4466
+ if (state.token) {
4467
+ if (!doctorSessionHandoff) await selectFastestServer({ silent: true, reconnect: false })
4468
+ overviewStarting=false
4469
+ openStreams()
4470
+ await Promise.all([refreshSessions(),refreshHostDescriptionDesktop()])
4471
+ refreshWorkbench({ silent: true })
4472
+ }
4473
+ overviewStarting=false
4474
+ renderOverviewDesktop()
4475
+ }
4476
+
4477
+ start()
4478
+ mountWorkflowDesktop()
4479
+
4480
+ function mountWorkflowDesktop() {
4481
+ window.DshWorkflow?.mount({
4482
+ desktop:true, start:()=>{if(state.view==='view-overview')showView('view-sessions')},
4483
+ snapshot:()=>({token:!!state.token,host:currentServerEntry()?.note || state.server || location.host,
4484
+ gateway:activeGatewayHealth()?.ok || !!state.streamsOk?.mux,dsh:dshReachable(),
4485
+ mux:!!state.streamsOk?.mux,hostEvents:!!state.streamsOk?.host,pending:state.approvals.length+state.questions.length,
4486
+ busy:!!state.byId.get(state.current)?.running,sending:sendMessage.pending?.has(state.history)}),
4487
+ settings:name=>{showView('view-settings');showSettingsPage(name)},plugins:()=>showView('view-plugins'),
4488
+ feedback:openFeedbackModal,
4489
+ doctor:openDoctor,
4490
+ browse:()=>{closeNewSessionModal();showView('view-files')},
4491
+ register:async()=>{
4492
+ const connection=captureConnection(),path=state.fs.path;if(!path)return toast('请先选择主机目录','err')
4493
+ try{const value=await rpc('workspace.create',{path});if(!connection.valid()||!value?.workspace)return
4494
+ state.workspaces=[...state.workspaces.filter(w=>w.workspaceId!==value.workspace.workspaceId),value.workspace]
4495
+ closeWorkspaceModal();renderNewSessionWorkspace(value.workspace.workspaceId);await createSessionInWorkspace()
4496
+ }catch(error){if(connection.valid())toast(error.message,'err')}
4497
+ },
4498
+ command:runSlashCommand,send:sendMessage,refresh:refreshSessions,retry:()=>{startOverviewDetection(true);void refreshSessions()},
4499
+ operations:()=>{const connection=captureConnection();return {url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid}},
4500
+ relay:()=>{const connection=captureConnection();return {url:()=>apiUrl('/admin/api/relay'),headers:{authorization:'Bearer '+connection.token},valid:connection.valid,connected:!!connection.token}},
4501
+ discover:()=>{if(confirm('登记当前绑定目录下的子目录为工作区?'))void refreshWorkbench({discover:true})},
4502
+ files:()=>{const cwd=sessionCwd(state.byId.get(state.current));if(!cwd)return toast('当前会话没有工作目录','err');state.fs.loaded=true;showView('view-files');void loadFs(cwd,true)},
4503
+ admin:()=>window.open(new URL(apiUrl('/admin/'),location.href).href,'_blank','noopener,noreferrer'),
4504
+ approvalRecords: renderApprovalRecordsDesktop,
4505
+ clearApprovalRecords: resetApprovalRecords,
4506
+ clear:async kind=>{
4507
+ const en=window.I18N?.lang==='en'
4508
+ const messages={history:en?'Clear cached history? Host records will be kept.':'清除本机历史缓存?主机记录保留。',images:en?'Clear cached images? Images will download again when viewed.':'清除本机图片缓存?再次查看时会重新下载。',caches:en?'Clear history and image caches? Connections and preferences will be kept.':'清除本机历史和图片缓存?保留连接、凭证与偏好设置。',connection:en?'Remove this connection, credential and its caches?':'移除当前地址、保存的凭证及其缓存?其他连接条目保留。',all:en?'Clear all local Remote settings, credentials and caches?':'清除本机全部 Remote 配置、凭证与缓存?主机数据保留。'}
4509
+ const text=messages[kind]
4510
+ if(!confirm(text))return
4511
+ clearTimeout(scheduleHistoryCacheSave._t)
4512
+ if(kind==='connection'){
4513
+ const connection=captureConnection(),scope=historyCacheScope()
4514
+ cancelHistoryLoad()
4515
+ await window.DshImageCache.clear(scope);await window.DshHistory.cacheClear(scope)
4516
+ if(!connection.valid())return
4517
+ const current=currentServerEntry();if(current)state.servers=state.servers.filter(s=>s.id!==current.id)
4518
+ state.groupActive[state.activeGroup]='';state.token='';state.server='';LS.del('token');LS.del('server');saveServers()
4519
+ closeStream('mux');closeStream('host');stopPolling();renderServers();showView('view-settings');showSettingsPage('servers');return
4520
+ }
4521
+ const results=[]
4522
+ if(kind!=='images')cancelHistoryLoad()
4523
+ if(kind!=='images')results.push(await window.DshHistory.cacheClear())
4524
+ if(kind!=='history')results.push(await window.DshImageCache.clear())
4525
+ if(kind==='all'){window.DshWorkflow.clearStorage();location.reload()}
4526
+ else if(results.includes(false))toast(en?'Some caches could not be cleared. Retry shortly.':'部分缓存未能清除,请稍后重试。','err')
4527
+ else toast(en?'Cache cleared':'缓存已清除','ok')
4528
+ },
4529
+ recover:(row,receipt)=>{const value=receipt.result?.result?.value;if(row.method==='session.create'&&value?.sessionId)void openSession(value.sessionId);if(row.sessionId===state.current)void resyncCurrentSession()},
4530
+ })
4531
+ }
4532
+
4533
+ // Operation logs stay on this device; users can copy or export them.
4534
+ 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()})})
4535
+ globalThis.DshFileInbox?.mount({ capture: captureConnection, url: apiUrl,
4536
+ context: () => ({ sessionId: state.current, inChat: state.view === 'view-chat' }),
4537
+ sessionTitle: id => state.byId.has(id) ? titleOf(state.byId.get(id)) : '', openFiles: () => showView('view-files'),
4538
+ headers: connection => ({ authorization: 'Bearer ' + connection.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }), native: () => null })
4539
+ globalThis.DshSessionDeck?.mount({ context: () => ({ sessionId: state.current, inChat: state.view === 'view-chat' }) })
4540
+ globalThis.DshApprovalSummary?.mount({ capture: captureConnection, items: () => state.approvals,
4541
+ url: (connection, path) => connection.server + path,
4542
+ headers: connection => ({ authorization: 'Bearer ' + connection.token, ...clientIdHeaders() }) })
4543
+ globalThis.DshCacheUpgrade?.mount({
4544
+ scopes:()=>state.servers.map(server=>historyCacheScope(server.url,serverToken(server))),
4545
+ safe:()=>!state.current&&!state.approvals.length&&!state.questions.length
4546
+ &&![...document.querySelectorAll('textarea,input:not([type="checkbox"]):not([type="radio"])')].some(input=>input.getBoundingClientRect().width&&input.value)
4547
+ &&!document.querySelector('[data-transfer-id]')&&!state.sessions.some(session=>session.running)
4548
+ })