dsh-lite 0.0.0-stage → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/app.js ADDED
@@ -0,0 +1,3870 @@
1
+ import {
2
+ applyStaticTranslations,
3
+ currentLanguage,
4
+ goalPhaseLabel,
5
+ initLanguage,
6
+ languageToggleLabel,
7
+ languageToggleText,
8
+ setLanguage,
9
+ t,
10
+ } from './i18n.js?v=29'
11
+ import {
12
+ COLOR_MODES,
13
+ THEME_CHANGE_EVENT,
14
+ THEME_FAMILIES,
15
+ getTheme,
16
+ initTheme,
17
+ setColorMode,
18
+ setThemeFamily,
19
+ toggleColorMode,
20
+ } from './theme.js?v=29'
21
+ import { buildAnswerBatch, hasOptions, isAnswered } from './question-answers.js?v=29'
22
+
23
+ const API = {
24
+ bootstrap: '/api/lite/bootstrap',
25
+ session: '/api/lite/session',
26
+ insights: '/api/lite/insights',
27
+ history: '/api/lite/history',
28
+ queue: '/api/lite/queue',
29
+ commands: '/api/lite/commands',
30
+ command: '/api/lite/command',
31
+ prompt: '/api/lite/prompt',
32
+ model: '/api/lite/model',
33
+ cancel: '/api/lite/cancel',
34
+ new: '/api/lite/new',
35
+ fork: '/api/lite/fork',
36
+ permissions: '/api/lite/permissions',
37
+ rename: '/api/lite/rename',
38
+ archive: '/api/lite/archive',
39
+ unarchive: '/api/lite/unarchive',
40
+ pin: '/api/lite/pin',
41
+ archived: '/api/lite/archived',
42
+ sessions: '/api/lite/sessions',
43
+ answer: '/api/lite/answer',
44
+ approval: '/api/lite/approval',
45
+ }
46
+
47
+ const STORAGE = {
48
+ session: 'dsh-lite:session',
49
+ bootstrap: 'dsh-lite:bootstrap',
50
+ preset: 'dsh-lite:preset',
51
+ drafts: 'dsh-lite:drafts',
52
+ notify: 'dsh-lite:notify',
53
+ listView: 'dsh-lite:list-view',
54
+ listSort: 'dsh-lite:list-sort',
55
+ listArchived: 'dsh-lite:list-archived',
56
+ listCollapsed: 'dsh-lite:list-collapsed',
57
+ }
58
+
59
+ const GROUP_WATERLINE = 5
60
+ const MAX_DRAFT_CHARS = 16_000
61
+ const MAX_PENDING_IMAGES = 4
62
+ const MAX_IMAGE_LONG_EDGE = 1600
63
+ const MAX_IMAGE_BYTES = 2 * 1024 * 1024
64
+ const MAX_IMAGE_SOURCE_BYTES = 20 * 1024 * 1024
65
+ const HIDDEN_POLL_MS = 30_000
66
+
67
+ const state = {
68
+ bootstrap: null,
69
+ sessionId: null,
70
+ session: null,
71
+ timer: null,
72
+ pollToken: 0,
73
+ sending: false,
74
+ authError: false,
75
+ bannerTimer: null,
76
+ installPrompt: null,
77
+ modelSignature: '',
78
+ messageSignature: '',
79
+ history: [],
80
+ historyCursor: null,
81
+ historyHasMore: true,
82
+ historyLoading: false,
83
+ historyInitialized: false,
84
+ sessionCursor: null,
85
+ loadingSession: 0,
86
+ queueEditingId: null,
87
+ queueDraft: '',
88
+ queueSignature: '',
89
+ commands: null,
90
+ commandsSessionId: null,
91
+ commandsAt: 0,
92
+ commandMenuToken: 0,
93
+ sessionFilter: '',
94
+ goalEditing: false,
95
+ modelRefreshing: false,
96
+ effortSignature: '',
97
+ archivedFilter: 'hide',
98
+ listView: 'grouped',
99
+ listSort: 'recent',
100
+ collapsedGroups: new Set(),
101
+ groupWatermarks: new Map(),
102
+ viewMenuOpen: false,
103
+ archived: [],
104
+ archivedLoading: false,
105
+ archivedLoadedAt: 0,
106
+ archivedTotal: 0,
107
+ archivedHasMore: false,
108
+ archivedToken: 0,
109
+ activeExtra: [],
110
+ activeTotal: 0,
111
+ activeHasMore: false,
112
+ activeLoadingMore: false,
113
+ activeToken: 0,
114
+ searchRows: [],
115
+ searchTotal: 0,
116
+ searchHasMore: false,
117
+ searchLoading: false,
118
+ searchQuery: '',
119
+ searchScope: '',
120
+ searchOffsets: { active: 0, archived: 0 },
121
+ searchToken: 0,
122
+ searchTimer: null,
123
+ pagedSearch: false,
124
+ drafts: {},
125
+ draftTimer: null,
126
+ questionSignature: '',
127
+ questionSubmitting: false,
128
+ answeredCalls: new Set(),
129
+ approvalSignature: '',
130
+ approvalSubmitting: false,
131
+ pendingImages: [],
132
+ imageBusy: false,
133
+ notifyEnabled: false,
134
+ unread: false,
135
+ linkedSessionId: null,
136
+ appearanceOpen: false,
137
+ dialogResolve: null,
138
+ dialogLastFocus: null,
139
+ }
140
+
141
+ class ApiError extends Error {
142
+ constructor(code, message) {
143
+ super(message)
144
+ this.code = code
145
+ }
146
+ }
147
+
148
+ const el = {
149
+ title: document.getElementById('sessionTitle'),
150
+ subtitle: document.getElementById('sessionSubtitle'),
151
+ messages: document.getElementById('messages'),
152
+ empty: document.getElementById('emptyState'),
153
+ emptyText: document.getElementById('emptyText'),
154
+ runningBar: document.getElementById('runningBar'),
155
+ runningText: document.getElementById('runningText'),
156
+ waitingBar: document.getElementById('waitingBar'),
157
+ stop: document.getElementById('stopButton'),
158
+ prompt: document.getElementById('promptInput'),
159
+ send: document.getElementById('sendButton'),
160
+ imageButton: document.getElementById('imageButton'),
161
+ imageInput: document.getElementById('imageInput'),
162
+ imageTray: document.getElementById('imageTray'),
163
+ banner: document.getElementById('banner'),
164
+ contextMeter: document.getElementById('contextMeter'),
165
+ planChip: document.getElementById('planChip'),
166
+ modelSelect: document.getElementById('modelSelect'),
167
+ effortSelect: document.getElementById('effortSelect'),
168
+ modelRefresh: document.getElementById('modelRefresh'),
169
+ modelStatus: document.getElementById('modelStatus'),
170
+ sessionsButton: document.getElementById('sessionsButton'),
171
+ refreshButton: document.getElementById('refreshButton'),
172
+ sheet: document.getElementById('sessionSheet'),
173
+ sessionList: document.getElementById('sessionList'),
174
+ sheetSubtitle: document.getElementById('sheetSubtitle'),
175
+ newSessionButton: document.getElementById('newSessionButton'),
176
+ themeToggle: document.getElementById('themeToggle'),
177
+ appearanceButton: document.getElementById('appearanceButton'),
178
+ appearancePanel: document.getElementById('appearancePanel'),
179
+ appearanceClose: document.getElementById('appearanceClose'),
180
+ themeFamilyOptions: document.getElementById('themeFamilyOptions'),
181
+ themeModeOptions: document.getElementById('themeModeOptions'),
182
+ langToggle: document.getElementById('langToggle'),
183
+ fullPageButton: document.getElementById('fullPageButton'),
184
+ notifyToggle: document.getElementById('notifyToggle'),
185
+ notifyLabel: document.getElementById('notifyLabel'),
186
+ sessionSearchBar: document.getElementById('sessionSearchBar'),
187
+ listToolbar: document.getElementById('listToolbar'),
188
+ viewMenuButton: document.getElementById('viewMenuButton'),
189
+ viewSummary: document.getElementById('viewSummary'),
190
+ viewMenu: document.getElementById('viewMenu'),
191
+ viewArchivedCount: document.getElementById('viewArchivedCount'),
192
+ goalBar: document.getElementById('goalBar'),
193
+ goalToggle: document.getElementById('goalToggle'),
194
+ goalSummary: document.getElementById('goalSummary'),
195
+ goalPhase: document.getElementById('goalPhase'),
196
+ goalPause: document.getElementById('goalPause'),
197
+ goalEdit: document.getElementById('goalEdit'),
198
+ goalDelete: document.getElementById('goalDelete'),
199
+ goalEditor: document.getElementById('goalEditor'),
200
+ goalInput: document.getElementById('goalInput'),
201
+ goalSave: document.getElementById('goalSave'),
202
+ goalCancel: document.getElementById('goalCancel'),
203
+ historyBar: document.getElementById('historyBar'),
204
+ loadEarlier: document.getElementById('loadEarlier'),
205
+ queueBar: document.getElementById('queueBar'),
206
+ presetBar: document.getElementById('presetBar'),
207
+ presetSelect: document.getElementById('presetSelect'),
208
+ workspaceBar: document.getElementById('workspaceBar'),
209
+ workspaceSelect: document.getElementById('workspaceSelect'),
210
+ sessionSearchBar: document.getElementById('sessionSearchBar'),
211
+ sessionSearch: document.getElementById('sessionSearch'),
212
+ scrollWrap: document.getElementById('scrollBottomWrap'),
213
+ scrollBottom: document.getElementById('scrollBottom'),
214
+ commandMenu: document.getElementById('commandMenu'),
215
+ commandMenuList: document.getElementById('commandMenuList'),
216
+ questionCard: document.getElementById('questionCard'),
217
+ approvalCard: document.getElementById('approvalCard'),
218
+ listMore: document.getElementById('listMore'),
219
+ loadMoreButton: document.getElementById('loadMoreButton'),
220
+ listMoreHint: document.getElementById('listMoreHint'),
221
+ dialog: document.getElementById('dialog'),
222
+ dialogTitle: document.getElementById('dialogTitle'),
223
+ dialogMessage: document.getElementById('dialogMessage'),
224
+ dialogInput: document.getElementById('dialogInput'),
225
+ dialogActions: document.getElementById('dialogActions'),
226
+ }
227
+
228
+ function api(path, options = {}) {
229
+ return fetch(path, {
230
+ credentials: 'same-origin',
231
+ cache: 'no-store',
232
+ ...options,
233
+ }).then(async (response) => {
234
+ let data = null
235
+ try {
236
+ data = await response.json()
237
+ } catch {
238
+ // Non-JSON responses are transport/auth failures below.
239
+ }
240
+ if (response.status === 401 || response.status === 403) {
241
+ throw new ApiError('auth', data?.error?.message || t('未登录或 cookie 已过期'))
242
+ }
243
+ if (!response.ok) {
244
+ throw new ApiError(data?.error?.code || `http-${response.status}`, data?.error?.message || `HTTP ${response.status}`)
245
+ }
246
+ if (data === null || data.ok !== true) {
247
+ throw new ApiError(data?.error?.code || 'lite/error', data?.error?.message || t('请求失败'))
248
+ }
249
+ return data
250
+ })
251
+ }
252
+
253
+ function post(path, body) {
254
+ return api(path, {
255
+ method: 'POST',
256
+ headers: { 'content-type': 'application/json' },
257
+ body: JSON.stringify(body),
258
+ })
259
+ }
260
+
261
+ function showBanner(message, persistent = false, tone = 'error') {
262
+ el.banner.textContent = message
263
+ el.banner.dataset.tone = tone
264
+ el.banner.hidden = false
265
+ if (state.bannerTimer !== null) clearTimeout(state.bannerTimer)
266
+ state.bannerTimer = null
267
+ if (!persistent) {
268
+ state.bannerTimer = setTimeout(() => {
269
+ el.banner.hidden = true
270
+ state.bannerTimer = null
271
+ }, 6000)
272
+ }
273
+ }
274
+
275
+ function clearBanner() {
276
+ el.banner.hidden = true
277
+ el.banner.textContent = ''
278
+ if (state.bannerTimer !== null) {
279
+ clearTimeout(state.bannerTimer)
280
+ state.bannerTimer = null
281
+ }
282
+ }
283
+
284
+ function isAuthError(error) {
285
+ return error instanceof ApiError && error.code === 'auth'
286
+ }
287
+
288
+ function handleError(error) {
289
+ if (isAuthError(error)) {
290
+ state.authError = true
291
+ showBanner(t('未登录或 cookie 已过期:先在手机浏览器打开一次 DSH 完整页面(启动时打印的带 token 链接),再回来刷新。'), true)
292
+ return
293
+ }
294
+ showBanner(error instanceof Error ? error.message : String(error))
295
+ }
296
+
297
+ function authRecovered() {
298
+ if (!state.authError) return
299
+ state.authError = false
300
+ clearBanner()
301
+ }
302
+
303
+ function savedSessionId() {
304
+ try {
305
+ return localStorage.getItem(STORAGE.session)
306
+ } catch {
307
+ return null
308
+ }
309
+ }
310
+
311
+ function saveSessionId(id) {
312
+ try {
313
+ localStorage.setItem(STORAGE.session, id)
314
+ } catch {
315
+ // Private mode/localStorage refusal is non-fatal.
316
+ }
317
+ }
318
+
319
+ function linkedSessionId() {
320
+ try {
321
+ const value = new URL(location.href).searchParams.get('session')
322
+ return typeof value === 'string' && value.length > 0 ? value : null
323
+ } catch {
324
+ return null
325
+ }
326
+ }
327
+
328
+ /**
329
+ * Hand over to the full page on the same origin. The full page has no routes;
330
+ * it restores its selected session from the `dsh.sessions.current` snapshot
331
+ * store, so write the current session there first (best effort — a storage
332
+ * failure just opens the full page on whatever it had last).
333
+ */
334
+ function openFullPage() {
335
+ const sessionId = state.sessionId
336
+ if (typeof sessionId === 'string' && sessionId.length > 0) {
337
+ try {
338
+ localStorage.setItem('dsh.sessions.current', JSON.stringify({ sessionId }))
339
+ } catch {
340
+ // Private mode or quota: the full page still opens, on its last session.
341
+ }
342
+ }
343
+ location.assign('/')
344
+ }
345
+
346
+ function completionNotifyPreference() {
347
+ try {
348
+ return localStorage.getItem(STORAGE.notify) === '1'
349
+ } catch {
350
+ return false
351
+ }
352
+ }
353
+
354
+ function savedPresetId() {
355
+ try {
356
+ return localStorage.getItem(STORAGE.preset)
357
+ } catch {
358
+ return null
359
+ }
360
+ }
361
+
362
+ function savePresetId(id) {
363
+ try {
364
+ localStorage.setItem(STORAGE.preset, id)
365
+ } catch {
366
+ // Non-fatal.
367
+ }
368
+ }
369
+
370
+ function readListView() {
371
+ try {
372
+ return localStorage.getItem(STORAGE.listView) === 'flat' ? 'flat' : 'grouped'
373
+ } catch {
374
+ return 'grouped'
375
+ }
376
+ }
377
+
378
+ function saveListView(view) {
379
+ try {
380
+ localStorage.setItem(STORAGE.listView, view)
381
+ } catch {
382
+ // Non-fatal.
383
+ }
384
+ }
385
+
386
+ function readListSort() {
387
+ try {
388
+ const value = localStorage.getItem(STORAGE.listSort)
389
+ return value === 'title' || value === 'created' ? value : 'recent'
390
+ } catch {
391
+ return 'recent'
392
+ }
393
+ }
394
+
395
+ function saveListSort(sort) {
396
+ try {
397
+ localStorage.setItem(STORAGE.listSort, sort)
398
+ } catch {
399
+ // Non-fatal.
400
+ }
401
+ }
402
+
403
+ function readArchivedFilter() {
404
+ try {
405
+ const value = localStorage.getItem(STORAGE.listArchived)
406
+ return value === 'show' || value === 'only' ? value : 'hide'
407
+ } catch {
408
+ return 'hide'
409
+ }
410
+ }
411
+
412
+ function saveArchivedFilter(filter) {
413
+ try {
414
+ localStorage.setItem(STORAGE.listArchived, filter)
415
+ } catch {
416
+ // Non-fatal.
417
+ }
418
+ }
419
+
420
+ function readCollapsedGroups() {
421
+ try {
422
+ const raw = localStorage.getItem(STORAGE.listCollapsed)
423
+ const value = raw === null ? null : JSON.parse(raw)
424
+ if (!Array.isArray(value)) return new Set()
425
+ return new Set(value.filter((key) => typeof key === 'string').slice(0, 100))
426
+ } catch {
427
+ return new Set()
428
+ }
429
+ }
430
+
431
+ function saveCollapsedGroups() {
432
+ try {
433
+ localStorage.setItem(STORAGE.listCollapsed, JSON.stringify([...state.collapsedGroups]))
434
+ } catch {
435
+ // Non-fatal.
436
+ }
437
+ }
438
+
439
+ function readDrafts() {
440
+ try {
441
+ const raw = localStorage.getItem(STORAGE.drafts)
442
+ const value = raw === null ? null : JSON.parse(raw)
443
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return {}
444
+ const drafts = {}
445
+ for (const [key, text] of Object.entries(value)) {
446
+ if (typeof text === 'string' && text.length > 0) drafts[key] = text.slice(0, MAX_DRAFT_CHARS)
447
+ }
448
+ return drafts
449
+ } catch {
450
+ return {}
451
+ }
452
+ }
453
+
454
+ function writeDrafts() {
455
+ try {
456
+ const keys = Object.keys(state.drafts)
457
+ if (keys.length > 20) {
458
+ for (const key of keys.slice(0, keys.length - 20)) delete state.drafts[key]
459
+ }
460
+ localStorage.setItem(STORAGE.drafts, JSON.stringify(state.drafts))
461
+ } catch {
462
+ // Non-fatal.
463
+ }
464
+ }
465
+
466
+ function scheduleDraftWrite() {
467
+ if (state.draftTimer !== null) return
468
+ state.draftTimer = setTimeout(() => {
469
+ state.draftTimer = null
470
+ writeDrafts()
471
+ }, 400)
472
+ }
473
+
474
+ function saveCurrentDraft() {
475
+ const key = state.sessionId ?? '__new__'
476
+ const text = el.prompt.value
477
+ if (text.length === 0) delete state.drafts[key]
478
+ else state.drafts[key] = text.slice(0, MAX_DRAFT_CHARS)
479
+ scheduleDraftWrite()
480
+ }
481
+
482
+ function restoreDraft() {
483
+ const key = state.sessionId ?? '__new__'
484
+ el.prompt.value = state.drafts[key] ?? ''
485
+ resizePrompt()
486
+ }
487
+
488
+ function clearDraft(sessionId) {
489
+ const key = sessionId ?? '__new__'
490
+ if (state.drafts[key] === undefined) return
491
+ delete state.drafts[key]
492
+ writeDrafts()
493
+ }
494
+
495
+ function clearPendingImages() {
496
+ state.pendingImages = []
497
+ renderImageTray()
498
+ }
499
+
500
+ function renderImageTray() {
501
+ el.imageTray.replaceChildren()
502
+ if (state.pendingImages.length === 0) {
503
+ el.imageTray.hidden = true
504
+ return
505
+ }
506
+ el.imageTray.hidden = false
507
+ for (const image of state.pendingImages) {
508
+ const chip = document.createElement('div')
509
+ chip.className = 'image-chip'
510
+ chip.title = image.name
511
+ const preview = document.createElement('img')
512
+ preview.src = `data:${image.mediaType};base64,${image.data}`
513
+ preview.alt = image.name
514
+ preview.loading = 'lazy'
515
+ const remove = document.createElement('button')
516
+ remove.type = 'button'
517
+ remove.className = 'image-chip-remove'
518
+ remove.textContent = '×'
519
+ remove.setAttribute('aria-label', t('移除图片 {name}', { name: image.name }))
520
+ remove.addEventListener('click', () => {
521
+ state.pendingImages = state.pendingImages.filter((candidate) => candidate.id !== image.id)
522
+ renderImageTray()
523
+ })
524
+ chip.append(preview, remove)
525
+ el.imageTray.append(chip)
526
+ }
527
+ }
528
+
529
+ async function addImages(files) {
530
+ const available = MAX_PENDING_IMAGES - state.pendingImages.length
531
+ if (available <= 0) {
532
+ showBanner(t('最多发送 {max} 张图片', { max: MAX_PENDING_IMAGES }))
533
+ return
534
+ }
535
+ const list = [...files].slice(0, available)
536
+ if (list.length === 0) return
537
+ state.imageBusy = true
538
+ el.imageButton.disabled = true
539
+ const errors = []
540
+ showBanner(t('正在处理图片…'), true)
541
+ try {
542
+ for (const file of list) {
543
+ try {
544
+ const image = await compressImage(file)
545
+ if (state.pendingImages.length >= MAX_PENDING_IMAGES) break
546
+ state.pendingImages.push(image)
547
+ renderImageTray()
548
+ } catch (error) {
549
+ errors.push(error instanceof Error ? error.message : t('图片处理失败'))
550
+ }
551
+ }
552
+ } finally {
553
+ state.imageBusy = false
554
+ el.imageButton.disabled = false
555
+ clearBanner()
556
+ if (files.length > available) showBanner(t('最多发送 {max} 张图片,已取前 {count} 张', { max: MAX_PENDING_IMAGES, count: available }))
557
+ else if (errors.length > 0) showBanner(errors[0])
558
+ }
559
+ }
560
+
561
+ async function compressImage(file) {
562
+ if (!file.type.startsWith('image/')) throw new Error(t('只支持图片文件'))
563
+ if (file.size > MAX_IMAGE_SOURCE_BYTES) throw new Error(t('原图超过 20 MB,请先缩小'))
564
+ const bitmap = await createImageBitmap(file).catch(async () => {
565
+ const url = URL.createObjectURL(file)
566
+ try {
567
+ const image = new Image()
568
+ image.src = url
569
+ await image.decode()
570
+ return image
571
+ } finally {
572
+ URL.revokeObjectURL(url)
573
+ }
574
+ }).catch(() => {
575
+ throw new Error(t('浏览器无法读取这张图片'))
576
+ })
577
+ const width = bitmap.naturalWidth || bitmap.width
578
+ const height = bitmap.naturalHeight || bitmap.height
579
+ if (!(width > 0) || !(height > 0)) {
580
+ bitmap.close?.()
581
+ throw new Error(t('图片尺寸无效'))
582
+ }
583
+ let blob = await scaleToBlob(bitmap, MAX_IMAGE_LONG_EDGE, 0.84)
584
+ if (blob === null) {
585
+ bitmap.close?.()
586
+ throw new Error(t('图片压缩失败'))
587
+ }
588
+ if (blob.size > MAX_IMAGE_BYTES) {
589
+ const smaller = await scaleToBlob(bitmap, Math.min(1200, MAX_IMAGE_LONG_EDGE), 0.7)
590
+ if (smaller !== null) blob = smaller
591
+ }
592
+ bitmap.close?.()
593
+ if (blob.size > MAX_IMAGE_BYTES) throw new Error(t('压缩后仍超过 2 MB,请选择更小的图片'))
594
+ const data = await blobToBase64(blob)
595
+ return {
596
+ id: typeof globalThis.crypto?.randomUUID === 'function' ? globalThis.crypto.randomUUID() : `${Date.now()}-${Math.random()}`,
597
+ name: typeof file.name === 'string' && file.name.length > 0 ? file.name.slice(0, 120) : 'image',
598
+ mediaType: blob.type,
599
+ data,
600
+ bytes: blob.size,
601
+ }
602
+ }
603
+
604
+ async function scaleToBlob(bitmap, longEdge, quality) {
605
+ const sourceWidth = bitmap.naturalWidth || bitmap.width
606
+ const sourceHeight = bitmap.naturalHeight || bitmap.height
607
+ const scale = Math.min(1, longEdge / Math.max(sourceWidth, sourceHeight))
608
+ const canvas = document.createElement('canvas')
609
+ canvas.width = Math.max(1, Math.round(sourceWidth * scale))
610
+ canvas.height = Math.max(1, Math.round(sourceHeight * scale))
611
+ const context = canvas.getContext('2d')
612
+ if (context === null) return null
613
+ context.imageSmoothingQuality = 'high'
614
+ context.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
615
+ let blob = await canvasToBlob(canvas, 'image/webp', quality)
616
+ if (blob === null || blob.type !== 'image/webp') blob = await canvasToBlob(canvas, 'image/jpeg', quality)
617
+ return blob
618
+ }
619
+
620
+ function canvasToBlob(canvas, type, quality) {
621
+ return new Promise((resolve) => {
622
+ canvas.toBlob((blob) => resolve(blob), type, quality)
623
+ })
624
+ }
625
+
626
+ function blobToBase64(blob) {
627
+ return new Promise((resolve, reject) => {
628
+ const reader = new FileReader()
629
+ reader.onload = () => {
630
+ const result = typeof reader.result === 'string' ? reader.result : ''
631
+ const comma = result.indexOf(',')
632
+ if (comma < 0) reject(new Error(t('图片读取失败')))
633
+ else resolve(result.slice(comma + 1))
634
+ }
635
+ reader.onerror = () => reject(new Error(t('图片读取失败')))
636
+ reader.readAsDataURL(blob)
637
+ })
638
+ }
639
+
640
+ function familyText(family) {
641
+ return currentLanguage() === 'zh' ? family.label.zh : family.label.en
642
+ }
643
+
644
+ function modeText(mode) {
645
+ return currentLanguage() === 'zh' ? mode.label.zh : mode.label.en
646
+ }
647
+
648
+ function renderThemeToggle() {
649
+ const theme = getTheme()
650
+ el.themeToggle.setAttribute('aria-label', theme.resolvedMode === 'dark' ? t('切换为浅色主题') : t('切换为深色主题'))
651
+ }
652
+
653
+ function renderAppearanceOptions() {
654
+ if (el.themeFamilyOptions === null || el.themeModeOptions === null) return
655
+ const theme = getTheme()
656
+ const active = document.activeElement
657
+ const activeFamily = active instanceof HTMLElement && active.closest('#themeFamilyOptions') !== null
658
+ ? active.dataset.family
659
+ : null
660
+ const activeMode = active instanceof HTMLElement && active.closest('#themeModeOptions') !== null
661
+ ? active.dataset.mode
662
+ : null
663
+
664
+ el.themeFamilyOptions.textContent = ''
665
+ for (const family of THEME_FAMILIES) {
666
+ const selected = theme.family === family.id
667
+ const button = document.createElement('button')
668
+ button.type = 'button'
669
+ button.className = `appearance-option${selected ? ' is-selected' : ''}`
670
+ button.dataset.family = family.id
671
+ button.setAttribute('role', 'radio')
672
+ button.setAttribute('aria-checked', String(selected))
673
+ button.tabIndex = selected ? 0 : -1
674
+ button.title = currentLanguage() === 'zh' ? family.description.zh : family.description.en
675
+ const swatch = document.createElement('span')
676
+ swatch.className = 'appearance-swatch'
677
+ swatch.dataset.family = family.id
678
+ swatch.setAttribute('aria-hidden', 'true')
679
+ const label = document.createElement('span')
680
+ label.className = 'appearance-option-label'
681
+ label.textContent = familyText(family)
682
+ const hint = document.createElement('span')
683
+ hint.className = 'appearance-hint'
684
+ hint.textContent = selected ? '✓' : ''
685
+ button.append(swatch, label, hint)
686
+ button.addEventListener('click', () => {
687
+ if (getTheme().family === family.id) return
688
+ setThemeFamily(family.id)
689
+ })
690
+ el.themeFamilyOptions.append(button)
691
+ }
692
+
693
+ el.themeModeOptions.textContent = ''
694
+ for (const mode of COLOR_MODES) {
695
+ const selected = theme.mode === mode.id
696
+ const button = document.createElement('button')
697
+ button.type = 'button'
698
+ button.className = `appearance-mode${selected ? ' is-selected' : ''}`
699
+ button.dataset.mode = mode.id
700
+ button.setAttribute('role', 'radio')
701
+ button.setAttribute('aria-checked', String(selected))
702
+ button.tabIndex = selected ? 0 : -1
703
+ button.textContent = modeText(mode)
704
+ button.addEventListener('click', () => {
705
+ if (getTheme().mode === mode.id) return
706
+ setColorMode(mode.id)
707
+ })
708
+ el.themeModeOptions.append(button)
709
+ }
710
+
711
+ if (activeFamily !== null && activeFamily !== undefined) {
712
+ el.themeFamilyOptions.querySelector(`.appearance-option[data-family="${activeFamily}"]`)?.focus()
713
+ }
714
+ if (activeMode !== null && activeMode !== undefined) {
715
+ el.themeModeOptions.querySelector(`.appearance-mode[data-mode="${activeMode}"]`)?.focus()
716
+ }
717
+ }
718
+
719
+ function wireRadioGroup(container, selector) {
720
+ container.addEventListener('keydown', (event) => {
721
+ if (!['ArrowDown', 'ArrowRight', 'ArrowUp', 'ArrowLeft', 'Home', 'End'].includes(event.key)) return
722
+ const buttons = [...container.querySelectorAll(selector)]
723
+ const index = buttons.indexOf(document.activeElement)
724
+ if (index < 0) return
725
+ event.preventDefault()
726
+ let next = 0
727
+ if (event.key === 'End') next = buttons.length - 1
728
+ else if (event.key !== 'Home') {
729
+ const delta = event.key === 'ArrowDown' || event.key === 'ArrowRight' ? 1 : -1
730
+ next = (index + delta + buttons.length) % buttons.length
731
+ }
732
+ buttons[next].focus()
733
+ buttons[next].click()
734
+ })
735
+ }
736
+
737
+ function openAppearancePanel() {
738
+ if (state.appearanceOpen) return
739
+ closeViewMenu()
740
+ state.appearanceOpen = true
741
+ renderAppearanceOptions()
742
+ el.appearancePanel.hidden = false
743
+ el.appearanceButton.setAttribute('aria-expanded', 'true')
744
+ }
745
+
746
+ function closeAppearancePanel() {
747
+ if (!state.appearanceOpen) return
748
+ const hadFocus = el.appearancePanel.contains(document.activeElement)
749
+ state.appearanceOpen = false
750
+ el.appearancePanel.hidden = true
751
+ el.appearanceButton.setAttribute('aria-expanded', 'false')
752
+ if (hadFocus) el.appearanceButton.focus()
753
+ }
754
+
755
+ function toggleAppearancePanel() {
756
+ if (state.appearanceOpen) closeAppearancePanel()
757
+ else openAppearancePanel()
758
+ }
759
+
760
+ function renderLanguageToggle() {
761
+ el.langToggle.textContent = languageToggleText()
762
+ const label = languageToggleLabel()
763
+ el.langToggle.setAttribute('aria-label', label)
764
+ el.langToggle.title = label
765
+ }
766
+
767
+ function refreshForLanguage() {
768
+ state.messageSignature = ''
769
+ state.approvalSignature = ''
770
+ state.questionSignature = ''
771
+ state.queueSignature = ''
772
+ state.modelSignature = ''
773
+ el.modelStatus.textContent = ''
774
+ el.presetSelect.dataset.signature = ''
775
+ el.workspaceSelect.dataset.signature = ''
776
+ el.effortSelect.dataset.signature = ''
777
+ clearBanner()
778
+ renderLanguageToggle()
779
+ renderThemeToggle()
780
+ renderAppearanceOptions()
781
+ renderNotifyToggle()
782
+ renderModelOptions()
783
+ renderPresets()
784
+ renderWorkspaces()
785
+ if (state.session !== null) {
786
+ renderSession()
787
+ } else if (state.sessionId === null) {
788
+ renderIdle()
789
+ } else {
790
+ const row = findSession(state.sessionId)
791
+ if (row !== null) renderHeader(row)
792
+ else {
793
+ el.title.textContent = 'DSH Lite'
794
+ el.subtitle.textContent = t('加载中…')
795
+ }
796
+ }
797
+ renderSessionList()
798
+ }
799
+
800
+ function toggleLanguage() {
801
+ setLanguage(currentLanguage() === 'zh' ? 'en' : 'zh')
802
+ applyStaticTranslations()
803
+ refreshForLanguage()
804
+ }
805
+
806
+ function cachedBootstrap() {
807
+ try {
808
+ const raw = localStorage.getItem(STORAGE.bootstrap)
809
+ if (raw === null) return null
810
+ const value = JSON.parse(raw)
811
+ return value !== null && typeof value === 'object' && Array.isArray(value.sessions) ? value : null
812
+ } catch {
813
+ return null
814
+ }
815
+ }
816
+
817
+ function cacheBootstrap(value) {
818
+ try {
819
+ localStorage.setItem(STORAGE.bootstrap, JSON.stringify(value))
820
+ } catch {
821
+ // Non-fatal.
822
+ }
823
+ }
824
+
825
+ async function loadBootstrap(force = false) {
826
+ try {
827
+ const data = await api(`${API.bootstrap}${force ? '?refresh=1' : ''}`)
828
+ state.bootstrap = data
829
+ state.activeExtra = []
830
+ state.activeToken += 1
831
+ state.activeLoadingMore = false
832
+ state.activeTotal = Number.isInteger(data.activeTotal) ? data.activeTotal : data.sessions.length
833
+ state.activeHasMore = data.activeHasMore === true
834
+ state.pagedSearch = Number.isInteger(data.activeTotal)
835
+ cacheBootstrap(data)
836
+ authRecovered()
837
+ renderSessionList()
838
+ renderModelOptions()
839
+ renderPresets()
840
+ renderWorkspaces()
841
+ if (force && archivedVisible()) {
842
+ if (searching()) void runSearch(false)
843
+ else void loadArchivedSessions(true)
844
+ }
845
+ if (state.session !== null) {
846
+ syncModelSelect(state.session.model)
847
+ syncEffort(state.session.model)
848
+ }
849
+ if (state.sessionId === null) {
850
+ const candidate = state.linkedSessionId ?? savedSessionId()
851
+ const exists = data.sessions.some((session) => session.id === candidate)
852
+ if (candidate !== null && (exists || state.linkedSessionId !== null)) openSession(candidate)
853
+ else if (data.sessions.length > 0) openSession(data.sessions[0].id)
854
+ else renderEmpty(t('还没有会话。点左上角 ☰ → 新建。'))
855
+ state.linkedSessionId = null
856
+ }
857
+ return data
858
+ } catch (error) {
859
+ handleError(error)
860
+ return null
861
+ }
862
+ }
863
+
864
+ function findSession(id) {
865
+ return state.bootstrap?.sessions.find((session) => session.id === id)
866
+ ?? state.activeExtra.find((session) => session.id === id)
867
+ ?? state.archived.find((session) => session.id === id)
868
+ ?? state.searchRows.find((session) => session.id === id)
869
+ ?? null
870
+ }
871
+
872
+ function openSession(id) {
873
+ if (typeof id !== 'string' || id.length === 0) return
874
+ saveCurrentDraft()
875
+ state.sessionId = id
876
+ saveSessionId(id)
877
+ state.session = null
878
+ state.messageSignature = ''
879
+ state.history = []
880
+ state.historyCursor = null
881
+ state.historyHasMore = true
882
+ state.historyLoading = false
883
+ state.historyInitialized = false
884
+ state.sessionCursor = null
885
+ state.queueEditingId = null
886
+ state.queueDraft = ''
887
+ state.queueSignature = ''
888
+ state.commands = null
889
+ state.commandsSessionId = null
890
+ state.goalEditing = false
891
+ state.answeredCalls.clear()
892
+ clearPendingImages()
893
+ closeSheet()
894
+ restoreDraft()
895
+ renderHeader(findSession(id))
896
+ renderEmpty(t('加载中…'))
897
+ void loadSession()
898
+ }
899
+
900
+ async function loadSession() {
901
+ const id = state.sessionId
902
+ if (id === null) return
903
+ const token = ++state.pollToken
904
+ const after = state.sessionCursor
905
+ const query = after === null ? '' : `&after=${after}`
906
+ state.loadingSession += 1
907
+ try {
908
+ const data = await api(`${API.session}?id=${encodeURIComponent(id)}${query}`)
909
+ if (token !== state.pollToken || id !== state.sessionId) return
910
+ authRecovered()
911
+ const next = data.session
912
+ const previous = state.session
913
+ const previousMessages = Array.isArray(previous?.messages) ? previous.messages : []
914
+ const incoming = Array.isArray(next.messages) ? next.messages : []
915
+ const replacing = after === null || next.reset === true || previous === null || previous.id !== next.id
916
+ const messages = replacing
917
+ ? incoming
918
+ : incoming.length === 0
919
+ ? previousMessages
920
+ : mergeMessages(previousMessages, incoming)
921
+ const gap = typeof next.gap === 'boolean' ? next.gap : previous?.gap === true
922
+ const finished = previous?.id === next.id && previous.running === true && next.running !== true
923
+ if (replacing && after !== null) state.messageSignature = ''
924
+ state.session = { ...next, messages, gap }
925
+ state.sessionCursor = typeof next.cursor === 'number' && next.cursor >= 0 ? next.cursor : null
926
+ if (!state.historyInitialized || next.reset === true) {
927
+ state.historyCursor = typeof next.historyCursor === 'number' ? next.historyCursor : null
928
+ state.historyHasMore = next.historyHasMore === true
929
+ state.historyInitialized = true
930
+ }
931
+ renderSession()
932
+ if (finished) notifyTurnFinished(state.session)
933
+ schedulePoll(next.running ? 1500 : 12000)
934
+ } catch (error) {
935
+ if (token !== state.pollToken) return
936
+ handleError(error)
937
+ schedulePoll(12000)
938
+ } finally {
939
+ state.loadingSession = Math.max(0, state.loadingSession - 1)
940
+ }
941
+ }
942
+
943
+ function schedulePoll(delay) {
944
+ if (state.timer !== null) {
945
+ clearTimeout(state.timer)
946
+ state.timer = null
947
+ }
948
+ if (state.sessionId === null) return
949
+ if (document.visibilityState !== 'visible') {
950
+ // A hidden page normally stops polling. With completion notifications on,
951
+ // keep a slow poll only while a turn is running, so the page can notice the
952
+ // transition and fire a Notification. Browsers may still suspend it.
953
+ if (!completionNotificationsEnabled() || state.session?.running !== true) return
954
+ delay = Math.max(delay, HIDDEN_POLL_MS)
955
+ }
956
+ state.timer = setTimeout(() => {
957
+ state.timer = null
958
+ void loadSession()
959
+ }, delay)
960
+ }
961
+
962
+ function notificationsSupported() {
963
+ return typeof Notification !== 'undefined'
964
+ }
965
+
966
+ function completionNotificationsEnabled() {
967
+ return state.notifyEnabled && notificationsSupported() && Notification.permission === 'granted'
968
+ }
969
+
970
+ function renderNotifyToggle() {
971
+ if (!notificationsSupported()) {
972
+ el.notifyToggle.hidden = true
973
+ return
974
+ }
975
+ el.notifyToggle.hidden = false
976
+ const label = completionNotificationsEnabled() ? t('通知开') : t('通知关')
977
+ if (el.notifyLabel !== null) el.notifyLabel.textContent = label
978
+ el.notifyToggle.setAttribute('aria-label', label)
979
+ el.notifyToggle.title = t('本轮结束时提醒;页面关闭后不保证提醒')
980
+ el.notifyToggle.setAttribute('aria-pressed', String(completionNotificationsEnabled()))
981
+ }
982
+
983
+ function setUnread(value) {
984
+ state.unread = value
985
+ document.title = value ? '• DSH Lite' : 'DSH Lite'
986
+ }
987
+
988
+ function notifyTurnFinished(session) {
989
+ const waiting = session.waiting === true
990
+ if (document.visibilityState === 'visible') {
991
+ if (!waiting) showBanner(t('本轮已结束'), false, 'ok')
992
+ return
993
+ }
994
+ setUnread(true)
995
+ if (!completionNotificationsEnabled()) return
996
+ void showCompletionNotification(session, waiting ? t('模型正在等待你的回答或确认') : t('本轮已结束'))
997
+ }
998
+
999
+ async function showCompletionNotification(session, body) {
1000
+ const title = session.title || 'DSH Lite'
1001
+ const options = {
1002
+ body,
1003
+ tag: `dsh-lite-${session.id}`,
1004
+ icon: '/lite/icon-192.png',
1005
+ data: { sessionId: session.id },
1006
+ }
1007
+ try {
1008
+ if ('serviceWorker' in navigator) {
1009
+ const registration = await navigator.serviceWorker.getRegistration('/lite/')
1010
+ if (registration !== undefined) {
1011
+ await registration.showNotification(title, options)
1012
+ return
1013
+ }
1014
+ }
1015
+ } catch {
1016
+ // Fall back to the page-level constructor below.
1017
+ }
1018
+ try {
1019
+ new Notification(title, options)
1020
+ } catch {
1021
+ // Some mobile browsers only allow service-worker notifications.
1022
+ }
1023
+ }
1024
+
1025
+ async function toggleNotifications() {
1026
+ if (!notificationsSupported()) return
1027
+ if (completionNotificationsEnabled()) {
1028
+ state.notifyEnabled = false
1029
+ try { localStorage.setItem(STORAGE.notify, '0') } catch { /* non-fatal */ }
1030
+ renderNotifyToggle()
1031
+ showBanner(t('已关闭完成提醒'))
1032
+ return
1033
+ }
1034
+ let permission
1035
+ try {
1036
+ permission = Notification.permission
1037
+ if (permission === 'default') permission = await Notification.requestPermission()
1038
+ } catch {
1039
+ renderNotifyToggle()
1040
+ showBanner(t('浏览器不支持通知授权'))
1041
+ return
1042
+ }
1043
+ if (permission !== 'granted') {
1044
+ renderNotifyToggle()
1045
+ showBanner(t('浏览器没有授予通知权限'))
1046
+ return
1047
+ }
1048
+ state.notifyEnabled = true
1049
+ try { localStorage.setItem(STORAGE.notify, '1') } catch { /* non-fatal */ }
1050
+ renderNotifyToggle()
1051
+ showBanner(t('已开启完成提醒:页面在后台时可用,关闭页面后不保证'), false, 'ok')
1052
+ }
1053
+
1054
+ function renderHeader(row) {
1055
+ el.title.textContent = row?.title || 'DSH Lite'
1056
+ setSubtitle(row?.cwd, row?.running, row?.live, row?.archived)
1057
+ el.goalBar.hidden = true
1058
+ el.goalBar.classList.remove('expanded')
1059
+ el.goalToggle.setAttribute('aria-expanded', 'false')
1060
+ el.goalSummary.textContent = ''
1061
+ el.goalEditor.hidden = true
1062
+ state.goalEditing = false
1063
+ el.queueBar.hidden = true
1064
+ el.contextMeter.hidden = true
1065
+ hideCommandMenu()
1066
+ hideQuestionCard()
1067
+ hideApprovalCard()
1068
+ }
1069
+
1070
+ function renderIdle() {
1071
+ el.title.textContent = 'DSH Lite'
1072
+ el.subtitle.textContent = t('选择或新建一个会话')
1073
+ el.subtitle.dataset.state = 'idle'
1074
+ el.contextMeter.hidden = true
1075
+ el.planChip.hidden = true
1076
+ el.goalBar.hidden = true
1077
+ el.queueBar.hidden = true
1078
+ el.runningBar.hidden = true
1079
+ el.waitingBar.hidden = true
1080
+ el.historyBar.hidden = true
1081
+ hideQuestionCard()
1082
+ hideApprovalCard()
1083
+ }
1084
+
1085
+ function setSubtitle(cwd, running, live, archived) {
1086
+ const parts = []
1087
+ const name = basenameOf(cwd)
1088
+ if (name) parts.push(name)
1089
+ parts.push(archived ? t('已归档') : running ? t('运行中') : live ? t('空闲') : t('冷会话'))
1090
+ el.subtitle.textContent = parts.join(' · ')
1091
+ el.subtitle.title = typeof cwd === 'string' ? cwd : ''
1092
+ el.subtitle.dataset.state = archived ? 'archived' : running ? 'running' : live ? 'live' : 'cold'
1093
+ }
1094
+
1095
+ function renderEmpty(text) {
1096
+ el.empty.hidden = false
1097
+ el.emptyText.textContent = text
1098
+ el.messages.replaceChildren()
1099
+ el.runningBar.hidden = true
1100
+ el.waitingBar.hidden = true
1101
+ el.historyBar.hidden = true
1102
+ el.queueBar.hidden = true
1103
+ el.scrollWrap.hidden = true
1104
+ hideCommandMenu()
1105
+ hideQuestionCard()
1106
+ hideApprovalCard()
1107
+ }
1108
+
1109
+ function formatElapsed(startedAt) {
1110
+ if (typeof startedAt !== 'number' || !Number.isFinite(startedAt)) return ''
1111
+ const seconds = Math.max(0, Math.floor((Date.now() - startedAt) / 1000))
1112
+ if (seconds > 24 * 60 * 60) return ''
1113
+ if (seconds < 60) return `${seconds}s`
1114
+ const minutes = Math.floor(seconds / 60)
1115
+ if (minutes < 60) return `${minutes}:${String(seconds % 60).padStart(2, '0')}`
1116
+ const hours = Math.floor(minutes / 60)
1117
+ return `${hours}h${String(minutes % 60).padStart(2, '0')}`
1118
+ }
1119
+
1120
+ function activityText(session) {
1121
+ const activity = session?.activity
1122
+ if (activity === null || typeof activity !== 'object') return t('运行中…')
1123
+ const elapsed = formatElapsed(activity.startedAt)
1124
+ if (activity.kind === 'tool') {
1125
+ const parts = [t('运行中'), typeof activity.name === 'string' ? activity.name : 'tool']
1126
+ if (typeof activity.target === 'string' && activity.target.length > 0) parts.push(activity.target)
1127
+ if (Number.isInteger(activity.count) && activity.count > 1) parts.push(`+${activity.count - 1}`)
1128
+ if (elapsed) parts.push(elapsed)
1129
+ return parts.join(' · ')
1130
+ }
1131
+ if (activity.kind === 'thinking') {
1132
+ return elapsed ? t('正在生成回复… · {elapsed}', { elapsed }) : t('正在生成回复…')
1133
+ }
1134
+ return t('运行中…')
1135
+ }
1136
+
1137
+ function renderSession() {
1138
+ const session = state.session
1139
+ if (session === null) return
1140
+ const row = findSession(session.id) || session
1141
+ el.title.textContent = session.title || row.title || t('会话')
1142
+ setSubtitle(session.cwd, session.running, session.live, session.archived)
1143
+ renderContext(session.context)
1144
+ renderPlan(session.plan)
1145
+ renderGoal(session)
1146
+
1147
+ const messages = conversationMessages(session)
1148
+ const last = messages[messages.length - 1]
1149
+ const lastText = last?.text ?? ''
1150
+ const signature = [
1151
+ messages.length,
1152
+ last?.role ?? '',
1153
+ last?.seq ?? '',
1154
+ lastText.length,
1155
+ lastText.slice(0, 48),
1156
+ lastText.slice(-48),
1157
+ session.running ? '1' : '0',
1158
+ session.waiting ? '1' : '0',
1159
+ session.model ? `${session.model.provider}/${session.model.model}` : '',
1160
+ ].join('\u0000')
1161
+
1162
+ if (signature !== state.messageSignature) {
1163
+ state.messageSignature = signature
1164
+ renderMessages(session, messages)
1165
+ }
1166
+
1167
+ renderQueue(session)
1168
+ renderApprovals(session)
1169
+ renderQuestions(session, session.live === true)
1170
+ updateHistoryBar(messages)
1171
+ el.runningBar.hidden = !session.running
1172
+ const runningLabel = activityText(session)
1173
+ el.runningText.textContent = runningLabel
1174
+ el.runningText.title = runningLabel
1175
+ el.waitingBar.hidden = !session.waiting ||
1176
+ hasHeldApproval(session) ||
1177
+ (session.live === true && hasAnswerableQuestions(session))
1178
+ el.stop.disabled = !session.running
1179
+ el.send.disabled = state.sending || state.sessionId === null
1180
+ syncModelSelect(session.model)
1181
+ syncEffort(session.model)
1182
+ updateScrollButton()
1183
+ }
1184
+
1185
+ function isAnswerableCall(call) {
1186
+ return call?.state === 'continued' || call?.state === 'live'
1187
+ }
1188
+
1189
+ function hasAnswerableQuestions(session) {
1190
+ const calls = Array.isArray(session?.questions) ? session.questions : []
1191
+ return calls.some((call) => isAnswerableCall(call) && Array.isArray(call.questions) && call.questions.length > 0)
1192
+ }
1193
+
1194
+ function hideQuestionCard() {
1195
+ state.questionSignature = ''
1196
+ state.questionSubmitting = false
1197
+ el.questionCard.hidden = true
1198
+ el.questionCard.replaceChildren()
1199
+ }
1200
+
1201
+ function hideApprovalCard() {
1202
+ state.approvalSignature = ''
1203
+ state.approvalSubmitting = false
1204
+ el.approvalCard.hidden = true
1205
+ el.approvalCard.replaceChildren()
1206
+ }
1207
+
1208
+ function hasHeldApproval(session) {
1209
+ return Array.isArray(session?.approval) && session.approval.length > 0
1210
+ }
1211
+
1212
+ function approvalReason(row) {
1213
+ const zh = typeof row?.displayReason?.zh === 'string' ? row.displayReason.zh : ''
1214
+ const en = typeof row?.displayReason?.en === 'string' ? row.displayReason.en : ''
1215
+ const lang = (document.documentElement.lang || navigator.language || '').toLowerCase()
1216
+ const localized = lang.startsWith('zh') ? (zh || en) : (en || zh)
1217
+ if (localized) return localized
1218
+ return typeof row?.reason === 'string' ? row.reason : ''
1219
+ }
1220
+
1221
+ function renderApprovals(session) {
1222
+ const rows = Array.isArray(session?.approval) ? session.approval : []
1223
+ const signature = JSON.stringify(rows)
1224
+ if (signature === state.approvalSignature) return
1225
+ state.approvalSignature = signature
1226
+ el.approvalCard.replaceChildren()
1227
+ if (rows.length === 0) {
1228
+ el.approvalCard.hidden = true
1229
+ return
1230
+ }
1231
+ el.approvalCard.hidden = false
1232
+ const head = document.createElement('div')
1233
+ head.className = 'question-head approval-head'
1234
+ const kicker = document.createElement('span')
1235
+ kicker.className = 'question-kicker approval-kicker'
1236
+ kicker.textContent = t('需要确认')
1237
+ const note = document.createElement('span')
1238
+ note.className = 'question-note'
1239
+ note.textContent = t('只批准这一次,不改变权限设置')
1240
+ head.append(kicker, note)
1241
+ el.approvalCard.append(head)
1242
+
1243
+ const active = document.activeElement
1244
+ const editing = active !== null && (active.tagName === 'TEXTAREA' || active.tagName === 'INPUT')
1245
+ let focused = false
1246
+ for (const row of rows) {
1247
+ if (row === null || typeof row !== 'object' || typeof row.id !== 'string') continue
1248
+ const form = document.createElement('div')
1249
+ form.className = 'question-call approval-call'
1250
+
1251
+ const title = document.createElement('div')
1252
+ title.className = 'approval-title'
1253
+ const label = document.createElement('span')
1254
+ label.className = 'approval-title-label'
1255
+ label.textContent = t('工具请求执行')
1256
+ const tool = document.createElement('code')
1257
+ tool.className = 'approval-tool'
1258
+ tool.textContent = typeof row.toolName === 'string' && row.toolName.length > 0 ? row.toolName : 'tool'
1259
+ title.append(label, tool)
1260
+ form.append(title)
1261
+
1262
+ const reason = approvalReason(row)
1263
+ if (reason) {
1264
+ const text = document.createElement('div')
1265
+ text.className = 'question-text approval-reason'
1266
+ text.textContent = reason
1267
+ form.append(text)
1268
+ }
1269
+ if (typeof row.reason === 'string' && row.reason.length > 0 && row.reason !== reason) {
1270
+ const details = document.createElement('details')
1271
+ details.className = 'question-detail approval-detail'
1272
+ const summary = document.createElement('summary')
1273
+ summary.textContent = t('查看原始原因')
1274
+ const body = document.createElement('div')
1275
+ body.className = 'question-detail-body'
1276
+ body.textContent = row.reason
1277
+ details.append(summary, body)
1278
+ form.append(details)
1279
+ }
1280
+
1281
+ const actions = document.createElement('div')
1282
+ actions.className = 'question-actions approval-actions'
1283
+ const reject = document.createElement('button')
1284
+ reject.type = 'button'
1285
+ reject.className = 'question-skip approval-reject'
1286
+ reject.textContent = t('拒绝')
1287
+ const allow = document.createElement('button')
1288
+ allow.type = 'button'
1289
+ allow.className = 'question-submit approval-allow'
1290
+ allow.textContent = t('允许一次')
1291
+ if (state.approvalSubmitting) {
1292
+ reject.disabled = true
1293
+ allow.disabled = true
1294
+ }
1295
+ reject.addEventListener('click', () => void submitApproval(session.id, row.id, 'reject', reject))
1296
+ allow.addEventListener('click', () => void submitApproval(session.id, row.id, 'allow', allow))
1297
+ actions.append(reject, allow)
1298
+ form.append(actions)
1299
+ el.approvalCard.append(form)
1300
+
1301
+ if (!focused && !editing) {
1302
+ focused = true
1303
+ requestAnimationFrame(() => {
1304
+ if (!reject.disabled && document.visibilityState === 'visible') reject.focus({ preventScroll: true })
1305
+ })
1306
+ }
1307
+ }
1308
+ }
1309
+
1310
+ async function submitApproval(sessionId, id, decision, activeButton) {
1311
+ if (state.approvalSubmitting) return
1312
+ state.approvalSubmitting = true
1313
+ const buttons = [...el.approvalCard.querySelectorAll('button')]
1314
+ for (const button of buttons) button.disabled = true
1315
+ const label = activeButton.textContent
1316
+ activeButton.textContent = decision === 'allow' ? t('允许中…') : t('拒绝中…')
1317
+ try {
1318
+ await post(API.approval, { sessionId, id, decision })
1319
+ if (state.session?.id === sessionId) {
1320
+ const approvals = Array.isArray(state.session.approval) ? state.session.approval : []
1321
+ state.session.approval = approvals.filter((row) => row.id !== id)
1322
+ const questions = Array.isArray(state.session.questions) ? state.session.questions : []
1323
+ state.session.waiting = questions.length > 0 || state.session.approval.length > 0
1324
+ }
1325
+ state.approvalSignature = ''
1326
+ renderSession()
1327
+ showBanner(decision === 'allow' ? t('已允许一次') : t('已拒绝'), false, 'ok')
1328
+ if (state.sessionId === sessionId) {
1329
+ await loadSession()
1330
+ schedulePoll(800)
1331
+ } else {
1332
+ await loadBootstrap(true)
1333
+ }
1334
+ } catch (error) {
1335
+ handleError(error)
1336
+ if (error instanceof ApiError && error.code === 'lite/approval-not-answerable') {
1337
+ state.approvalSignature = ''
1338
+ if (state.sessionId === sessionId) await loadSession()
1339
+ }
1340
+ } finally {
1341
+ state.approvalSubmitting = false
1342
+ for (const button of buttons) button.disabled = false
1343
+ activeButton.textContent = label
1344
+ }
1345
+ }
1346
+
1347
+ function renderQuestions(session, answerable) {
1348
+ const allCalls = answerable && Array.isArray(session?.questions) ? session.questions : []
1349
+ const present = new Set(allCalls.map((call) => call?.callId).filter((id) => typeof id === 'string'))
1350
+ for (const id of state.answeredCalls) {
1351
+ if (!present.has(id)) state.answeredCalls.delete(id)
1352
+ }
1353
+ const calls = allCalls
1354
+ .filter((call) => call !== null && typeof call === 'object' &&
1355
+ isAnswerableCall(call) && Array.isArray(call.questions) && call.questions.length > 0 &&
1356
+ !state.answeredCalls.has(call.callId))
1357
+ const openCount = allCalls.filter((call) =>
1358
+ call?.state === 'open' && Array.isArray(call.questions) && call.questions.length > 0).length
1359
+ const liveCount = calls.filter((call) => call.state === 'live').length
1360
+ const continuedCount = calls.length - liveCount
1361
+ const signature = JSON.stringify([answerable, calls, openCount])
1362
+ if (signature === state.questionSignature) return
1363
+ state.questionSignature = signature
1364
+ el.questionCard.replaceChildren()
1365
+ if (calls.length === 0) {
1366
+ el.questionCard.hidden = true
1367
+ return
1368
+ }
1369
+ el.questionCard.hidden = false
1370
+ const head = document.createElement('div')
1371
+ head.className = 'question-head'
1372
+ const kicker = document.createElement('span')
1373
+ kicker.className = 'question-kicker'
1374
+ kicker.textContent = t('待回答')
1375
+ const note = document.createElement('span')
1376
+ note.className = 'question-note'
1377
+ const notes = []
1378
+ if (continuedCount > 0) notes.push(t('回答会作为新消息发给模型'))
1379
+ if (liveCount > 0) notes.push(t('回答会直接交给正在等待的模型'))
1380
+ if (openCount > 0) notes.push(t('另有 {count} 个问题等待完整页面', { count: openCount }))
1381
+ note.textContent = notes.join(' · ')
1382
+ head.append(kicker, note)
1383
+ el.questionCard.append(head)
1384
+
1385
+ for (const call of calls) {
1386
+ const form = document.createElement('div')
1387
+ form.className = 'question-call'
1388
+ const inputs = []
1389
+ for (const question of call.questions) {
1390
+ if (question === null || typeof question !== 'object' || typeof question.id !== 'string') continue
1391
+ const block = document.createElement('div')
1392
+ block.className = 'question-item'
1393
+ if (typeof question.header === 'string' && question.header.length > 0) {
1394
+ const header = document.createElement('div')
1395
+ header.className = 'question-item-header'
1396
+ header.textContent = question.header
1397
+ block.append(header)
1398
+ }
1399
+ const text = document.createElement('div')
1400
+ text.className = 'question-text'
1401
+ text.textContent = question.question ?? ''
1402
+ block.append(text)
1403
+ if (typeof question.detail === 'string' && question.detail.length > 0) {
1404
+ const details = document.createElement('details')
1405
+ details.className = 'question-detail'
1406
+ const summary = document.createElement('summary')
1407
+ summary.textContent = t('查看详情')
1408
+ const body = document.createElement('div')
1409
+ body.className = 'question-detail-body'
1410
+ body.textContent = question.detail
1411
+ details.append(summary, body)
1412
+ block.append(details)
1413
+ }
1414
+ const selected = new Set()
1415
+ const options = Array.isArray(question.options) ? question.options : []
1416
+ if (options.length > 0) {
1417
+ const list = document.createElement('div')
1418
+ list.className = 'question-options'
1419
+ const buttons = []
1420
+ for (const option of options) {
1421
+ if (option === null || typeof option !== 'object' || typeof option.label !== 'string') continue
1422
+ const button = document.createElement('button')
1423
+ button.type = 'button'
1424
+ button.className = 'question-option'
1425
+ button.setAttribute('aria-pressed', 'false')
1426
+ const label = document.createElement('span')
1427
+ label.className = 'question-option-label'
1428
+ label.textContent = option.label
1429
+ button.append(label)
1430
+ if (typeof option.description === 'string' && option.description.length > 0) {
1431
+ const description = document.createElement('span')
1432
+ description.className = 'question-option-desc'
1433
+ description.textContent = option.description
1434
+ button.append(description)
1435
+ }
1436
+ button.addEventListener('click', () => {
1437
+ // Choosing an option withdraws a skip, as on the host card.
1438
+ if (entry.skipped) setSkipped(false)
1439
+ if (question.multiSelect === true) {
1440
+ if (selected.has(option.label)) selected.delete(option.label)
1441
+ else selected.add(option.label)
1442
+ } else {
1443
+ const wasSelected = selected.has(option.label)
1444
+ selected.clear()
1445
+ if (!wasSelected) selected.add(option.label)
1446
+ }
1447
+ for (const item of buttons) {
1448
+ const on = selected.has(item.dataset.label)
1449
+ item.classList.toggle('selected', on)
1450
+ item.setAttribute('aria-pressed', String(on))
1451
+ }
1452
+ })
1453
+ button.dataset.label = option.label
1454
+ buttons.push(button)
1455
+ list.append(button)
1456
+ }
1457
+ block.append(list)
1458
+ }
1459
+ const custom = document.createElement('input')
1460
+ custom.type = 'text'
1461
+ custom.className = 'question-custom'
1462
+ custom.placeholder = options.length > 0 ? t('其他回答(可选)') : t('输入回答')
1463
+ custom.autocomplete = 'off'
1464
+ custom.maxLength = 2000
1465
+ block.append(custom)
1466
+ // Per-question skip: the host card's semantics — a skipped question is
1467
+ // an explicit empty answer, and the other questions keep their answers.
1468
+ const skipToggle = document.createElement('button')
1469
+ skipToggle.type = 'button'
1470
+ skipToggle.className = 'question-item-skip'
1471
+ skipToggle.setAttribute('aria-pressed', 'false')
1472
+ skipToggle.textContent = t('跳过此题')
1473
+ const entry = { question, selected, custom, skipped: false }
1474
+ const setSkipped = (on) => {
1475
+ entry.skipped = on
1476
+ block.classList.toggle('skipped', on)
1477
+ skipToggle.setAttribute('aria-pressed', String(on))
1478
+ skipToggle.textContent = on ? t('已跳过,点此撤销') : t('跳过此题')
1479
+ }
1480
+ skipToggle.addEventListener('click', () => setSkipped(!entry.skipped))
1481
+ custom.addEventListener('input', () => {
1482
+ if (entry.skipped) setSkipped(false)
1483
+ })
1484
+ block.append(skipToggle)
1485
+ inputs.push(entry)
1486
+ form.append(block)
1487
+ }
1488
+ if (inputs.length === 0) continue
1489
+ const actions = document.createElement('div')
1490
+ actions.className = 'question-actions'
1491
+ const submit = document.createElement('button')
1492
+ submit.type = 'button'
1493
+ submit.className = 'question-submit'
1494
+ submit.textContent = t('提交回答')
1495
+ const skipAll = document.createElement('button')
1496
+ skipAll.type = 'button'
1497
+ skipAll.className = 'question-skip'
1498
+ skipAll.textContent = t('全部跳过')
1499
+ const buttons = [submit, skipAll]
1500
+ submit.addEventListener('click', () => void submitAnswers(session.id, call.callId, inputs, buttons, submit, t('提交中…')))
1501
+ skipAll.addEventListener('click', () => void skipAllAnswers(session.id, call.callId, inputs, buttons, skipAll))
1502
+ actions.append(submit, skipAll)
1503
+ form.append(actions)
1504
+ el.questionCard.append(form)
1505
+ }
1506
+ }
1507
+
1508
+ function draftsOf(inputs) {
1509
+ return inputs.map((input) => ({ selected: input.selected, custom: input.custom.value, skipped: input.skipped }))
1510
+ }
1511
+
1512
+ function promptFor(question) {
1513
+ const params = { question: question.question ?? t('问题') }
1514
+ return hasOptions(question)
1515
+ ? t('请选择或输入回答,或跳过此题:{question}', params)
1516
+ : t('请输入回答,或跳过此题:{question}', params)
1517
+ }
1518
+
1519
+ async function submitAnswers(sessionId, callId, inputs, buttons, activeButton, pendingText) {
1520
+ if (state.questionSubmitting) return
1521
+ const batch = buildAnswerBatch(inputs.map((input) => input.question), draftsOf(inputs))
1522
+ if (batch.missing !== undefined) {
1523
+ const input = inputs[batch.missing]
1524
+ showBanner(promptFor(input.question))
1525
+ input.custom.focus()
1526
+ return
1527
+ }
1528
+ await sendAnswers(sessionId, callId, batch.answers, buttons, activeButton, pendingText, t('已提交回答'))
1529
+ }
1530
+
1531
+ async function skipAllAnswers(sessionId, callId, inputs, buttons, activeButton) {
1532
+ if (state.questionSubmitting) return
1533
+ const drafts = draftsOf(inputs)
1534
+ const answered = drafts.filter((draft) => isAnswered(draft)).length
1535
+ // Skipping everything discards drafted answers; make that a deliberate choice.
1536
+ if (answered > 0) {
1537
+ const confirmed = await showDialog({
1538
+ title: t('全部跳过'),
1539
+ message: t('已回答的 {count} 题将被丢弃,确定全部跳过?', { count: answered }),
1540
+ danger: true,
1541
+ confirmText: t('全部跳过'),
1542
+ })
1543
+ if (confirmed !== true) return
1544
+ }
1545
+ const questions = inputs.map((input) => input.question)
1546
+ const batch = buildAnswerBatch(questions, drafts.map((draft) => ({ ...draft, skipped: true })))
1547
+ await sendAnswers(sessionId, callId, batch.answers, buttons, activeButton, t('全部跳过中…'), t('已跳过'))
1548
+ }
1549
+
1550
+ async function sendAnswers(sessionId, callId, answers, buttons, activeButton, pendingText, doneText) {
1551
+ const idleText = activeButton.textContent
1552
+ state.questionSubmitting = true
1553
+ for (const button of buttons) button.disabled = true
1554
+ activeButton.textContent = pendingText
1555
+ try {
1556
+ await post(API.answer, { sessionId, callId, answers })
1557
+ state.answeredCalls.add(callId)
1558
+ if (state.session?.id === sessionId) {
1559
+ state.session.questions = (Array.isArray(state.session.questions) ? state.session.questions : [])
1560
+ .filter((call) => call.callId !== callId)
1561
+ state.session.waiting = state.session.questions.length > 0
1562
+ }
1563
+ state.questionSignature = ''
1564
+ renderSession()
1565
+ showBanner(doneText, false, 'ok')
1566
+ if (state.sessionId === sessionId) {
1567
+ await loadSession()
1568
+ schedulePoll(800)
1569
+ } else {
1570
+ await loadBootstrap(true)
1571
+ }
1572
+ } catch (error) {
1573
+ handleError(error)
1574
+ if (error instanceof ApiError && error.code === 'lite/question-not-answerable') {
1575
+ state.questionSignature = ''
1576
+ if (state.sessionId === sessionId) await loadSession()
1577
+ }
1578
+ } finally {
1579
+ state.questionSubmitting = false
1580
+ for (const button of buttons) button.disabled = false
1581
+ activeButton.textContent = idleText
1582
+ }
1583
+ }
1584
+
1585
+ function renderGoal(session) {
1586
+ const goal = session.goal
1587
+ if (goal === null || goal === undefined || typeof goal.objective !== 'string') {
1588
+ el.goalBar.hidden = true
1589
+ el.goalSummary.textContent = ''
1590
+ el.goalPhase.hidden = true
1591
+ el.goalEditor.hidden = true
1592
+ state.goalEditing = false
1593
+ return
1594
+ }
1595
+ el.goalBar.hidden = false
1596
+ if (el.goalSummary.textContent !== goal.objective) el.goalSummary.textContent = goal.objective
1597
+ const phase = goalPhaseLabel(goal.phase)
1598
+ const rounds = typeof goal.roundsStarted === 'number'
1599
+ ? typeof goal.maxGoalRounds === 'number'
1600
+ ? t('{rounds}/{max} 轮', { rounds: goal.roundsStarted, max: goal.maxGoalRounds })
1601
+ : t('{rounds} 轮', { rounds: goal.roundsStarted })
1602
+ : ''
1603
+ const phaseText = [phase, rounds].filter((part) => part.length > 0).join(' · ')
1604
+ el.goalPhase.hidden = phaseText.length === 0
1605
+ if (el.goalPhase.textContent !== phaseText) el.goalPhase.textContent = phaseText
1606
+ if (el.goalPhase.dataset.phase !== (goal.phase ?? '')) el.goalPhase.dataset.phase = goal.phase ?? ''
1607
+ const resumable = goal.phase === 'paused' || goal.phase === 'blocked'
1608
+ el.goalPause.textContent = resumable ? t('继续') : t('暂停')
1609
+ el.goalPause.hidden = goal.phase === 'complete'
1610
+ el.goalSummary.title = typeof goal.blockedReason === 'string' ? t('阻塞:{reason}', { reason: goal.blockedReason }) : ''
1611
+ el.goalEditor.hidden = !state.goalEditing
1612
+ }
1613
+
1614
+ function formatTokens(value) {
1615
+ if (typeof value !== 'number' || !Number.isFinite(value)) return '?'
1616
+ if (value >= 1_000_000) return `${Math.round(value / 100_000) / 10}M`
1617
+ if (value >= 1_000) return `${Math.round(value / 100) / 10}k`
1618
+ return String(Math.round(value))
1619
+ }
1620
+
1621
+ function renderPlan(plan) {
1622
+ const active = plan?.active === true
1623
+ const pending = plan?.pending === true
1624
+ el.planChip.hidden = !(active || pending)
1625
+ if (el.planChip.hidden) return
1626
+ el.planChip.textContent = pending ? 'Plan…' : 'Plan'
1627
+ el.planChip.disabled = pending
1628
+ el.planChip.title = pending ? t('计划模式切换中') : t('计划模式已开启,点按关闭')
1629
+ el.planChip.setAttribute('aria-pressed', String(active))
1630
+ }
1631
+
1632
+ function renderContext(context) {
1633
+ if (context === null || typeof context !== 'object' || typeof context.percent !== 'number') {
1634
+ el.contextMeter.hidden = true
1635
+ return
1636
+ }
1637
+ const percent = Math.max(0, Math.min(100, Math.round(context.percent)))
1638
+ el.contextMeter.hidden = false
1639
+ el.contextMeter.textContent = t('上下文 {percent}%', { percent })
1640
+ el.contextMeter.dataset.level = percent >= 85 ? 'danger' : percent >= 65 ? 'warn' : 'ok'
1641
+ el.contextMeter.title = t('上下文已用 {percent}%({used} / {window})', {
1642
+ percent,
1643
+ used: formatTokens(context.used),
1644
+ window: formatTokens(context.window),
1645
+ })
1646
+ }
1647
+
1648
+ async function changePermissions(session) {
1649
+ try {
1650
+ const data = await api(`${API.permissions}?id=${encodeURIComponent(session.id)}`)
1651
+ const options = Array.isArray(data.options) ? data.options : []
1652
+ if (options.length === 0) {
1653
+ showBanner(t('此宿主没有可切换的权限预设'))
1654
+ return
1655
+ }
1656
+ const current = typeof data.current === 'string' ? data.current : ''
1657
+ const currentName = options.find((option) => option.value === current)?.name ?? current
1658
+ const lines = [t('当前:{name}', { name: currentName || t('未知') })]
1659
+ for (const option of options) {
1660
+ if (typeof option.description === 'string' && option.description.length > 0) {
1661
+ lines.push(t('{name}:{description}', { name: option.name, description: option.description }))
1662
+ }
1663
+ }
1664
+ const actions = options.map((option) => ({
1665
+ label: `${option.name}${option.value === current ? t('(当前)') : ''}`,
1666
+ value: option.value,
1667
+ primary: option.value === current,
1668
+ }))
1669
+ actions.push({ label: t('取消'), value: null, cancel: true })
1670
+ const choice = await showDialog({
1671
+ title: t('权限模式'),
1672
+ message: lines.join('\n'),
1673
+ detail: true,
1674
+ vertical: true,
1675
+ actions,
1676
+ })
1677
+ if (choice === null || choice === current) return
1678
+ const result = await post(API.permissions, { sessionId: session.id, preset: choice })
1679
+ const name = result.options?.find((option) => option.value === result.current)?.name ?? result.current ?? choice
1680
+ showBanner(t('已切换为 {name}', { name }), false, 'ok')
1681
+ if (state.sessionId === session.id) void loadSession()
1682
+ } catch (error) {
1683
+ handleError(error)
1684
+ }
1685
+ }
1686
+
1687
+ async function showInsights(id = state.sessionId) {
1688
+ if (id === null) return
1689
+ try {
1690
+ const data = await api(`${API.insights}?id=${encodeURIComponent(id)}`)
1691
+ const insights = data.insights ?? {}
1692
+ const lines = []
1693
+ const context = insights.context
1694
+ if (context !== null && typeof context === 'object') {
1695
+ const percent = Math.max(0, Math.min(100, Math.round(context.percent)))
1696
+ lines.push(t('上下文:{percent}%({used} / {window})', {
1697
+ percent,
1698
+ used: formatTokens(context.used),
1699
+ window: formatTokens(context.window),
1700
+ }))
1701
+ }
1702
+ const usage = insights.usage
1703
+ if (usage !== null && typeof usage === 'object') {
1704
+ lines.push(t('累计输入:{value}', { value: formatTokens(usage.input) }))
1705
+ lines.push(t('累计输出:{value}', { value: formatTokens(usage.output) }))
1706
+ lines.push(t('缓存:读 {read} · 写 {write}', {
1707
+ read: formatTokens(usage.cacheRead),
1708
+ write: formatTokens(usage.cacheWrite),
1709
+ }))
1710
+ }
1711
+ const breakdown = insights.breakdown
1712
+ if (breakdown !== null && typeof breakdown === 'object') {
1713
+ lines.push(t('上下文构成:系统 {system} · 工具 {tools} · 消息 {messages}', {
1714
+ system: formatTokens(breakdown.system),
1715
+ tools: formatTokens(breakdown.tools),
1716
+ messages: formatTokens(breakdown.messages),
1717
+ }))
1718
+ }
1719
+ const plan = insights.plan
1720
+ if (plan !== null && typeof plan === 'object') {
1721
+ lines.push(t('计划模式:{state}', {
1722
+ state: plan.pending === true ? t('切换中') : plan.active === true ? t('已开启') : t('已关闭'),
1723
+ }))
1724
+ }
1725
+ if (lines.length === 0) lines.push(t('暂无可用的用量数据。'))
1726
+ await showDialog({
1727
+ title: t('运行信息'),
1728
+ message: lines.join('\n'),
1729
+ detail: true,
1730
+ vertical: true,
1731
+ actions: [{ label: t('关闭'), value: null, cancel: true, primary: true }],
1732
+ })
1733
+ } catch (error) {
1734
+ handleError(error)
1735
+ }
1736
+ }
1737
+
1738
+ function mergeMessages(...lists) {
1739
+ const merged = new Map()
1740
+ for (const list of lists) {
1741
+ for (const message of Array.isArray(list) ? list : []) {
1742
+ const key = typeof message.seq === 'number'
1743
+ ? `seq:${message.seq}`
1744
+ : `${message.role}:${message.time ?? ''}:${message.text}`
1745
+ if (!merged.has(key)) merged.set(key, message)
1746
+ }
1747
+ }
1748
+ return [...merged.values()].sort((left, right) => (left.seq ?? 0) - (right.seq ?? 0))
1749
+ }
1750
+
1751
+ function conversationMessages(session) {
1752
+ return mergeMessages(state.history, session.messages)
1753
+ }
1754
+
1755
+ function updateHistoryBar() {
1756
+ const show = state.historyHasMore === true && typeof state.historyCursor === 'number' && state.historyCursor > 0
1757
+ el.historyBar.hidden = !show
1758
+ el.loadEarlier.disabled = state.historyLoading
1759
+ el.loadEarlier.textContent = state.historyLoading ? t('加载中…') : t('加载上一段')
1760
+ }
1761
+
1762
+ function renderMessages(session, messages) {
1763
+ const scroller = el.messages.parentElement
1764
+ const nearBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 80
1765
+ el.messages.replaceChildren()
1766
+ if (messages.length === 0) {
1767
+ el.empty.hidden = false
1768
+ el.emptyText.textContent = session.running ? t('等待第一条消息…') : t('这个会话还没有消息。')
1769
+ } else {
1770
+ el.empty.hidden = true
1771
+ let gapNoteShown = false
1772
+ for (const message of messages) {
1773
+ el.messages.append(bubble(message.role, message.text))
1774
+ if (!gapNoteShown && session.gap && state.history.length === 0 && message.role === 'user') {
1775
+ const note = document.createElement('div')
1776
+ note.className = 'gap-note'
1777
+ note.textContent = t('中间还有更多消息,点「加载上一段」补齐')
1778
+ el.messages.append(note)
1779
+ gapNoteShown = true
1780
+ }
1781
+ }
1782
+ }
1783
+ if (nearBottom) requestAnimationFrame(() => {
1784
+ scroller.scrollTop = scroller.scrollHeight
1785
+ })
1786
+ updateScrollButton()
1787
+ }
1788
+
1789
+ function updateScrollButton() {
1790
+ const scroller = el.messages.parentElement
1791
+ if (scroller === null) return
1792
+ const distance = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight
1793
+ el.scrollWrap.hidden = distance < 260
1794
+ }
1795
+
1796
+ function bubble(role, text) {
1797
+ const node = document.createElement('div')
1798
+ node.className = `bubble ${role}`
1799
+ if (role === 'assistant') node.innerHTML = renderMarkdown(text)
1800
+ else node.textContent = text
1801
+ return node
1802
+ }
1803
+
1804
+ function renderMarkdown(text) {
1805
+ const lines = String(text).replaceAll('\r\n', '\n').split('\n')
1806
+ let html = ''
1807
+ let index = 0
1808
+ while (index < lines.length) {
1809
+ const line = lines[index]
1810
+ if (/^\s*$/.test(line)) {
1811
+ index += 1
1812
+ continue
1813
+ }
1814
+ if (/^```/.test(line)) {
1815
+ const language = /^```([A-Za-z0-9+#._-]*)/.exec(line)?.[1] ?? ''
1816
+ index += 1
1817
+ const code = []
1818
+ while (index < lines.length && !/^```\s*$/.test(lines[index])) {
1819
+ code.push(lines[index])
1820
+ index += 1
1821
+ }
1822
+ index += 1
1823
+ const label = language.length > 0
1824
+ ? `<span class="code-lang">${escapeHtml(language)}</span>`
1825
+ : ''
1826
+ html += `<div class="code-block">${label}<button class="code-copy" type="button" aria-label="${escapeHtml(t('复制代码'))}">${escapeHtml(t('复制'))}</button><pre><code>${escapeHtml(code.join('\n'))}</code></pre></div>`
1827
+ continue
1828
+ }
1829
+ const heading = /^(#{1,4})\s+(.*?)\s*#*\s*$/.exec(line)
1830
+ if (heading !== null) {
1831
+ const level = Math.min(6, heading[1].length + 2)
1832
+ html += `<h${level}>${renderInline(heading[2])}</h${level}>`
1833
+ index += 1
1834
+ continue
1835
+ }
1836
+ if (/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/.test(line)) {
1837
+ html += '<hr>'
1838
+ index += 1
1839
+ continue
1840
+ }
1841
+ if (isTableStart(lines, index)) {
1842
+ const header = splitTableRow(line)
1843
+ index += 2
1844
+ const body = []
1845
+ while (index < lines.length && lines[index].includes('|') && !/^\s*$/.test(lines[index]) && !/^```/.test(lines[index])) {
1846
+ body.push(splitTableRow(lines[index]))
1847
+ index += 1
1848
+ }
1849
+ const headHtml = header.map((cell) => `<th>${renderInline(cell)}</th>`).join('')
1850
+ const bodyHtml = body.map((cells) => `<tr>${cells.map((cell) => `<td>${renderInline(cell)}</td>`).join('')}</tr>`).join('')
1851
+ html += `<div class="table-wrap"><table><thead><tr>${headHtml}</tr></thead>${bodyHtml.length > 0 ? `<tbody>${bodyHtml}</tbody>` : ''}</table></div>`
1852
+ continue
1853
+ }
1854
+ if (/^\s*[-*+]\s+/.test(line)) {
1855
+ const items = []
1856
+ while (index < lines.length && /^\s*[-*+]\s+/.test(lines[index])) {
1857
+ items.push(`<li>${renderInline(lines[index].replace(/^\s*[-*+]\s+/, ''))}</li>`)
1858
+ index += 1
1859
+ }
1860
+ html += `<ul>${items.join('')}</ul>`
1861
+ continue
1862
+ }
1863
+ if (/^\s*\d+[.)]\s+/.test(line)) {
1864
+ const items = []
1865
+ while (index < lines.length && /^\s*\d+[.)]\s+/.test(lines[index])) {
1866
+ items.push(`<li>${renderInline(lines[index].replace(/^\s*\d+[.)]\s+/, ''))}</li>`)
1867
+ index += 1
1868
+ }
1869
+ html += `<ol>${items.join('')}</ol>`
1870
+ continue
1871
+ }
1872
+ if (/^\s*>\s?/.test(line)) {
1873
+ const quote = []
1874
+ while (index < lines.length && /^\s*>\s?/.test(lines[index])) {
1875
+ quote.push(lines[index].replace(/^\s*>\s?/, ''))
1876
+ index += 1
1877
+ }
1878
+ html += `<blockquote>${renderInline(quote.join('\n'))}</blockquote>`
1879
+ continue
1880
+ }
1881
+ const paragraph = []
1882
+ while (index < lines.length && !/^\s*$/.test(lines[index]) && !blockStart(lines[index]) && !isTableStart(lines, index)) {
1883
+ paragraph.push(lines[index])
1884
+ index += 1
1885
+ }
1886
+ if (paragraph.length === 0) {
1887
+ paragraph.push(lines[index])
1888
+ index += 1
1889
+ }
1890
+ html += `<p>${renderInline(paragraph.join('\n'))}</p>`
1891
+ }
1892
+ return html
1893
+ }
1894
+
1895
+ function isTableStart(lines, index) {
1896
+ if (index + 1 >= lines.length) return false
1897
+ const header = lines[index]
1898
+ const separator = lines[index + 1]
1899
+ if (!header.includes('|') || !separator.includes('|')) return false
1900
+ return /^\s*\|?\s*:?-{2,}:?\s*(?:\|\s*:?-{2,}:?\s*)+\|?\s*$/.test(separator)
1901
+ }
1902
+
1903
+ function splitTableRow(line) {
1904
+ let text = line.trim()
1905
+ if (text.startsWith('|')) text = text.slice(1)
1906
+ if (text.endsWith('|')) text = text.slice(0, -1)
1907
+ return text.split('|').map((cell) => cell.trim())
1908
+ }
1909
+
1910
+ function blockStart(line) {
1911
+ return /^(?:```|#{1,4}\s|>\s?|\s*[-*+]\s+|\s*\d+[.)]\s+|\s*(?:-{3,}|\*{3,}|_{3,})\s*$)/.test(line)
1912
+ }
1913
+
1914
+ function renderInline(text) {
1915
+ return escapeHtml(text)
1916
+ .replace(/`([^`\n]+)`/g, '<code>$1</code>')
1917
+ .replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>')
1918
+ .replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>')
1919
+ .replace(/~~([^~\n]+)~~/g, '<del>$1</del>')
1920
+ .replace(/\n/g, '<br>')
1921
+ }
1922
+
1923
+ function escapeHtml(text) {
1924
+ return String(text)
1925
+ .replaceAll('&', '&amp;')
1926
+ .replaceAll('<', '&lt;')
1927
+ .replaceAll('>', '&gt;')
1928
+ .replaceAll('"', '&quot;')
1929
+ .replaceAll("'", '&#39;')
1930
+ }
1931
+
1932
+ async function copyText(text) {
1933
+ try {
1934
+ if (navigator.clipboard?.writeText !== undefined) {
1935
+ await navigator.clipboard.writeText(text)
1936
+ return true
1937
+ }
1938
+ } catch {
1939
+ // Clipboard API needs a secure context; fall through to the legacy path.
1940
+ }
1941
+ const area = document.createElement('textarea')
1942
+ area.className = 'copy-area'
1943
+ area.value = text
1944
+ area.setAttribute('readonly', '')
1945
+ document.body.append(area)
1946
+ area.select()
1947
+ area.setSelectionRange(0, text.length)
1948
+ let copied = false
1949
+ try {
1950
+ copied = document.execCommand('copy')
1951
+ } catch {
1952
+ copied = false
1953
+ }
1954
+ area.remove()
1955
+ return copied
1956
+ }
1957
+
1958
+ function archivedCount() {
1959
+ if (state.archivedLoadedAt > 0 && Number.isInteger(state.archivedTotal)) return state.archivedTotal
1960
+ const value = state.bootstrap?.archivedCount
1961
+ return Number.isInteger(value) && value >= 0 ? value : state.archived.length
1962
+ }
1963
+
1964
+ function sessionTone(id) {
1965
+ let hash = 0
1966
+ for (let index = 0; index < id.length; index += 1) hash = (hash * 31 + id.charCodeAt(index)) | 0
1967
+ return Math.abs(hash) % 6
1968
+ }
1969
+
1970
+ function firstGlyph(title) {
1971
+ const value = String(title ?? '').trim()
1972
+ return Array.from(value)[0] ?? '·'
1973
+ }
1974
+
1975
+ function mergeSessionRows(...lists) {
1976
+ const merged = new Map()
1977
+ for (const list of lists) {
1978
+ for (const row of Array.isArray(list) ? list : []) {
1979
+ if (row !== null && typeof row === 'object' && typeof row.id === 'string') merged.set(row.id, row)
1980
+ }
1981
+ }
1982
+ return [...merged.values()]
1983
+ }
1984
+
1985
+ function activeSessions() {
1986
+ return mergeSessionRows(state.bootstrap?.sessions ?? [], state.activeExtra)
1987
+ }
1988
+
1989
+ function normalizeWorkspacePath(value) {
1990
+ const path = String(value ?? '').trim().replace(/\/+$/, '')
1991
+ return path.length === 0 && String(value ?? '').startsWith('/') ? '/' : path
1992
+ }
1993
+
1994
+ let workspaceIndexCache = { source: null, byId: new Map(), byPath: new Map() }
1995
+
1996
+ function workspaceIndex() {
1997
+ const source = state.bootstrap
1998
+ if (workspaceIndexCache.source === source) return workspaceIndexCache
1999
+ const byId = new Map()
2000
+ const byPath = new Map()
2001
+ const list = Array.isArray(source?.workspaces) ? source.workspaces : []
2002
+ for (const [index, workspace] of list.entries()) {
2003
+ if (workspace === null || typeof workspace !== 'object' || typeof workspace.id !== 'string') continue
2004
+ const entry = {
2005
+ id: workspace.id,
2006
+ title: typeof workspace.title === 'string' && workspace.title.length > 0
2007
+ ? workspace.title
2008
+ : String(workspace.path ?? workspace.id),
2009
+ path: typeof workspace.path === 'string' ? workspace.path : '',
2010
+ order: index,
2011
+ }
2012
+ byId.set(entry.id, entry)
2013
+ if (entry.path.length > 0) byPath.set(normalizeWorkspacePath(entry.path), entry)
2014
+ }
2015
+ workspaceIndexCache = { source, byId, byPath }
2016
+ return workspaceIndexCache
2017
+ }
2018
+
2019
+ /**
2020
+ * Resolve the Workspace for one row. A payload carrying `workspaceId` (even
2021
+ * null) is authoritative. Older hosts omit the field entirely; those rows fall
2022
+ * back to an exact canonical-cwd match, which mirrors the registry's own
2023
+ * header validation and avoids an all-ungrouped list before a restart.
2024
+ */
2025
+ function sessionWorkspace(session, index = workspaceIndex()) {
2026
+ if (Object.hasOwn(session, 'workspaceId')) {
2027
+ const id = session.workspaceId
2028
+ if (typeof id !== 'string' || id.length === 0) return null
2029
+ return index.byId.get(id) ?? {
2030
+ id,
2031
+ title: typeof session.workspaceTitle === 'string' && session.workspaceTitle.length > 0
2032
+ ? session.workspaceTitle
2033
+ : id,
2034
+ path: '',
2035
+ order: 10_000,
2036
+ }
2037
+ }
2038
+ const cwd = normalizeWorkspacePath(session.cwd)
2039
+ return cwd.length > 0 ? index.byPath.get(cwd) ?? null : null
2040
+ }
2041
+
2042
+ function filterQuery() {
2043
+ return state.sessionFilter.trim()
2044
+ }
2045
+
2046
+ function searching() {
2047
+ return filterQuery().length > 0
2048
+ }
2049
+
2050
+ function archivedOnly() {
2051
+ return state.archivedFilter === 'only'
2052
+ }
2053
+
2054
+ function archivedVisible() {
2055
+ return state.archivedFilter !== 'hide'
2056
+ }
2057
+
2058
+ function searchScopes() {
2059
+ if (archivedOnly()) return ['archived']
2060
+ if (archivedVisible()) return ['active', 'archived']
2061
+ return ['active']
2062
+ }
2063
+
2064
+ function listSessions() {
2065
+ if (searching()) return state.searchRows
2066
+ if (archivedOnly()) return state.archived
2067
+ const active = activeSessions()
2068
+ return archivedVisible() ? mergeSessionRows(active, state.archived) : active
2069
+ }
2070
+
2071
+ function listTotal() {
2072
+ if (searching()) return state.searchTotal || state.searchRows.length
2073
+ const activeTotal = Number.isInteger(state.bootstrap?.activeTotal)
2074
+ ? state.bootstrap.activeTotal
2075
+ : activeSessions().length
2076
+ if (archivedOnly()) {
2077
+ return Number.isInteger(state.archivedTotal) ? state.archivedTotal : state.archived.length
2078
+ }
2079
+ if (archivedVisible()) {
2080
+ const archivedTotal = Number.isInteger(state.archivedTotal) ? state.archivedTotal : state.archived.length
2081
+ return activeTotal + archivedTotal
2082
+ }
2083
+ return activeTotal
2084
+ }
2085
+
2086
+ function listHasMore() {
2087
+ if (searching()) return state.searchHasMore
2088
+ if (archivedOnly()) return state.archivedHasMore
2089
+ if (archivedVisible()) return state.activeHasMore || state.archivedHasMore
2090
+ return state.activeHasMore
2091
+ }
2092
+
2093
+ function listLoading() {
2094
+ if (searching()) return state.searchLoading && state.searchRows.length === 0
2095
+ if (archivedOnly()) return state.archivedLoading && state.archived.length === 0
2096
+ return false
2097
+ }
2098
+
2099
+ function listLoadingMore() {
2100
+ if (searching()) return state.searchLoading
2101
+ if (archivedOnly()) return state.archivedLoading
2102
+ if (archivedVisible()) return state.activeLoadingMore || state.archivedLoading
2103
+ return state.activeLoadingMore
2104
+ }
2105
+
2106
+ function updateListMore() {
2107
+ const show = listHasMore() && !listLoading()
2108
+ el.listMore.hidden = !show
2109
+ if (!show) return
2110
+ el.loadMoreButton.disabled = listLoadingMore()
2111
+ el.loadMoreButton.textContent = listLoadingMore() ? t('加载中…') : t('加载更多')
2112
+ el.listMoreHint.textContent = t('已加载 {shown} / {total}', {
2113
+ shown: listSessions().length,
2114
+ total: listTotal(),
2115
+ })
2116
+ }
2117
+
2118
+ function compareSessionRows(left, right) {
2119
+ const pinned = Number(right.pinned === true) - Number(left.pinned === true)
2120
+ if (pinned !== 0) return pinned
2121
+ if (state.listSort === 'title') {
2122
+ const byTitle = String(left.title ?? '').localeCompare(
2123
+ String(right.title ?? ''),
2124
+ currentLanguage() === 'zh' ? 'zh-CN' : 'en-US',
2125
+ { sensitivity: 'base', numeric: true },
2126
+ )
2127
+ if (byTitle !== 0) return byTitle
2128
+ } else if (state.listSort === 'created') {
2129
+ const byCreation = (right.createdAt ?? right.updatedAt ?? 0) - (left.createdAt ?? left.updatedAt ?? 0)
2130
+ if (byCreation !== 0) return byCreation
2131
+ }
2132
+ return (right.updatedAt ?? 0) - (left.updatedAt ?? 0)
2133
+ || String(left.id).localeCompare(String(right.id))
2134
+ }
2135
+
2136
+ function sessionGroups(sessions) {
2137
+ const index = workspaceIndex()
2138
+ const groups = new Map()
2139
+ for (const session of sessions) {
2140
+ const workspace = sessionWorkspace(session, index)
2141
+ const key = workspace?.id ?? ''
2142
+ let group = groups.get(key)
2143
+ if (group === undefined) {
2144
+ group = {
2145
+ key,
2146
+ title: workspace?.title ?? t('未分组'),
2147
+ order: workspace?.order ?? 10_001,
2148
+ sessions: [],
2149
+ }
2150
+ groups.set(key, group)
2151
+ }
2152
+ group.sessions.push(session)
2153
+ }
2154
+ const result = [...groups.values()]
2155
+ for (const group of result) group.sessions.sort(compareSessionRows)
2156
+ result.sort((left, right) => left.order - right.order
2157
+ || left.title.localeCompare(right.title, currentLanguage() === 'zh' ? 'zh-CN' : 'en-US'))
2158
+ return result
2159
+ }
2160
+
2161
+ function groupBaseline(group) {
2162
+ let required = GROUP_WATERLINE
2163
+ group.sessions.forEach((session, index) => {
2164
+ if (session.running === true && index < 50) required = Math.max(required, index + 1)
2165
+ })
2166
+ return required
2167
+ }
2168
+
2169
+ function groupWatermark(group) {
2170
+ return Math.max(groupBaseline(group), state.groupWatermarks.get(group.key) ?? 0)
2171
+ }
2172
+
2173
+ function expandGroupWatermark(group) {
2174
+ const watermark = Math.min(group.sessions.length, groupWatermark(group) + GROUP_WATERLINE)
2175
+ if (watermark > groupBaseline(group)) state.groupWatermarks.set(group.key, watermark)
2176
+ else state.groupWatermarks.delete(group.key)
2177
+ rerenderListPreservingScroll()
2178
+ }
2179
+
2180
+ function collapseGroupWatermark(group) {
2181
+ state.groupWatermarks.delete(group.key)
2182
+ rerenderListPreservingScroll()
2183
+ }
2184
+
2185
+ function listViewSummary() {
2186
+ const group = state.listView === 'grouped' ? t('工作区') : t('平铺')
2187
+ const sort = state.listSort === 'title'
2188
+ ? t('标题')
2189
+ : state.listSort === 'created'
2190
+ ? t('创建时间')
2191
+ : t('最近更新')
2192
+ let value = `${group} · ${sort}`
2193
+ if (archivedOnly()) value += ` · ${t('仅归档')}`
2194
+ else if (archivedVisible()) value += ` · ${t('含归档')}`
2195
+ return value
2196
+ }
2197
+
2198
+ function updateViewMenuState() {
2199
+ for (const button of el.viewMenu.querySelectorAll('[data-view-group]')) {
2200
+ const selected = button.dataset.viewGroup === state.listView
2201
+ button.classList.toggle('is-selected', selected)
2202
+ button.setAttribute('aria-checked', String(selected))
2203
+ }
2204
+ for (const button of el.viewMenu.querySelectorAll('[data-view-sort]')) {
2205
+ const selected = button.dataset.viewSort === state.listSort
2206
+ button.classList.toggle('is-selected', selected)
2207
+ button.setAttribute('aria-checked', String(selected))
2208
+ }
2209
+ for (const button of el.viewMenu.querySelectorAll('[data-view-archived]')) {
2210
+ const selected = button.dataset.viewArchived === state.archivedFilter
2211
+ button.classList.toggle('is-selected', selected)
2212
+ button.setAttribute('aria-checked', String(selected))
2213
+ }
2214
+ const archivedTotal = el.viewArchivedCount
2215
+ if (archivedTotal !== null) archivedTotal.textContent = archivedCount() > 0 ? String(archivedCount()) : ''
2216
+ }
2217
+
2218
+ function openViewMenu() {
2219
+ if (state.appearanceOpen) closeAppearancePanel()
2220
+ state.viewMenuOpen = true
2221
+ updateViewMenuState()
2222
+ el.viewMenu.hidden = false
2223
+ el.viewMenuButton.setAttribute('aria-expanded', 'true')
2224
+ }
2225
+
2226
+ function closeViewMenu() {
2227
+ if (!state.viewMenuOpen) return
2228
+ const hadFocus = el.viewMenu.contains(document.activeElement)
2229
+ state.viewMenuOpen = false
2230
+ el.viewMenu.hidden = true
2231
+ el.viewMenuButton.setAttribute('aria-expanded', 'false')
2232
+ if (hadFocus) el.viewMenuButton.focus()
2233
+ }
2234
+
2235
+ function toggleViewMenu() {
2236
+ if (state.viewMenuOpen) closeViewMenu()
2237
+ else openViewMenu()
2238
+ }
2239
+
2240
+ function updateListToolbar() {
2241
+ const show = searching() || (!listLoading() && (listTotal() > 0 || archivedCount() > 0))
2242
+ el.listToolbar.hidden = !show
2243
+ el.sessionSearchBar.hidden = !show
2244
+ if (!show) {
2245
+ closeViewMenu()
2246
+ return
2247
+ }
2248
+ const summary = listViewSummary()
2249
+ el.viewSummary.textContent = summary
2250
+ el.viewMenuButton.setAttribute('aria-label', t('列表视图选项:{value}', { value: summary }))
2251
+ el.viewMenuButton.title = t('列表视图选项:{value}', { value: summary })
2252
+ updateViewMenuState()
2253
+ }
2254
+
2255
+ function rerenderListPreservingScroll() {
2256
+ const top = el.sessionList.scrollTop
2257
+ renderSessionList()
2258
+ el.sessionList.scrollTop = top
2259
+ }
2260
+
2261
+ function toggleSessionGroup(key) {
2262
+ if (state.collapsedGroups.has(key)) state.collapsedGroups.delete(key)
2263
+ else state.collapsedGroups.add(key)
2264
+ saveCollapsedGroups()
2265
+ rerenderListPreservingScroll()
2266
+ }
2267
+
2268
+ function setListView(view) {
2269
+ if (view !== 'grouped' && view !== 'flat') return
2270
+ if (state.listView !== view) {
2271
+ state.listView = view
2272
+ saveListView(view)
2273
+ el.sessionList.scrollTop = 0
2274
+ renderSessionList()
2275
+ }
2276
+ closeViewMenu()
2277
+ }
2278
+
2279
+ function setListSort(sort) {
2280
+ if (sort !== 'recent' && sort !== 'created' && sort !== 'title') return
2281
+ if (state.listSort !== sort) {
2282
+ state.listSort = sort
2283
+ saveListSort(sort)
2284
+ el.sessionList.scrollTop = 0
2285
+ renderSessionList()
2286
+ }
2287
+ closeViewMenu()
2288
+ }
2289
+
2290
+ function setArchivedFilter(filter) {
2291
+ if (filter !== 'hide' && filter !== 'show' && filter !== 'only') return
2292
+ closeViewMenu()
2293
+ if (state.archivedFilter === filter) return
2294
+ state.archivedFilter = filter
2295
+ saveArchivedFilter(filter)
2296
+ resetSearch()
2297
+ el.sessionList.scrollTop = 0
2298
+ renderSessionList()
2299
+ if (filter !== 'hide') void loadArchivedSessions(true)
2300
+ }
2301
+
2302
+ function sessionGroupHeader(group) {
2303
+ const collapsed = state.collapsedGroups.has(group.key)
2304
+ const containsCurrent = group.sessions.some((session) => session.id === state.sessionId)
2305
+ const header = document.createElement('button')
2306
+ header.type = 'button'
2307
+ header.className = `session-group-header${containsCurrent ? ' is-current' : ''}${collapsed ? ' is-collapsed' : ''}`
2308
+ header.dataset.groupKey = group.key
2309
+ header.setAttribute('aria-expanded', String(!collapsed))
2310
+ header.setAttribute('aria-label', collapsed
2311
+ ? t('展开 {title}', { title: group.title })
2312
+ : t('折叠 {title}', { title: group.title }))
2313
+ header.addEventListener('click', () => toggleSessionGroup(group.key))
2314
+ const icon = document.createElement('span')
2315
+ icon.className = 'group-icon'
2316
+ icon.setAttribute('aria-hidden', 'true')
2317
+ const title = document.createElement('span')
2318
+ title.className = 'group-title'
2319
+ title.textContent = group.title
2320
+ const count = document.createElement('span')
2321
+ count.className = 'group-count'
2322
+ count.textContent = String(group.sessions.length)
2323
+ const chevron = document.createElement('span')
2324
+ chevron.className = 'group-chevron'
2325
+ chevron.setAttribute('aria-hidden', 'true')
2326
+ header.append(icon, title, count, chevron)
2327
+ return header
2328
+ }
2329
+
2330
+ function groupMoreButton(group) {
2331
+ const watermark = groupWatermark(group)
2332
+ const remaining = group.sessions.length - watermark
2333
+ const baseline = groupBaseline(group)
2334
+ const button = document.createElement('button')
2335
+ button.type = 'button'
2336
+ button.className = 'group-more'
2337
+ button.textContent = remaining > 0
2338
+ ? t('展开其余 {count}', { count: remaining })
2339
+ : t('收起')
2340
+ button.setAttribute('aria-expanded', String(remaining === 0))
2341
+ button.addEventListener('click', () => {
2342
+ if (remaining > 0) expandGroupWatermark(group)
2343
+ else if (watermark > baseline) collapseGroupWatermark(group)
2344
+ })
2345
+ return button
2346
+ }
2347
+
2348
+ function renderSessionList() {
2349
+ updateListToolbar()
2350
+ const sessions = listSessions()
2351
+ const total = listTotal()
2352
+ const query = filterQuery()
2353
+ const loading = listLoading()
2354
+ const grouped = state.listView === 'grouped' && query.length === 0
2355
+ el.sessionList.classList.toggle('is-grouped', grouped)
2356
+ el.sessionList.replaceChildren()
2357
+ if (loading) {
2358
+ el.sheetSubtitle.textContent = query.length > 0 ? t('搜索中…') : t('加载已归档会话…')
2359
+ for (let index = 0; index < 4; index += 1) {
2360
+ const row = document.createElement('div')
2361
+ row.className = 'session-skeleton'
2362
+ const avatar = document.createElement('span')
2363
+ avatar.className = 'skeleton-avatar'
2364
+ const lines = document.createElement('span')
2365
+ lines.className = 'skeleton-lines'
2366
+ lines.append(document.createElement('span'), document.createElement('span'))
2367
+ row.append(avatar, lines)
2368
+ el.sessionList.append(row)
2369
+ }
2370
+ updateListMore()
2371
+ return
2372
+ }
2373
+ if (query.length > 0) {
2374
+ el.sheetSubtitle.textContent = state.searchLoading ? t('搜索中…') : t('匹配 {total} 个', { total })
2375
+ } else if (archivedOnly()) {
2376
+ el.sheetSubtitle.textContent = t('{total} 个已归档会话', { total })
2377
+ } else if (archivedVisible()) {
2378
+ el.sheetSubtitle.textContent = t('{total} 个会话 · 含归档', { total })
2379
+ } else {
2380
+ el.sheetSubtitle.textContent = total === 0
2381
+ ? t('暂无会话')
2382
+ : total > sessions.length
2383
+ ? t('共 {total} 个 · 已显示 {shown}', { total, shown: sessions.length })
2384
+ : t('最近 {total} 个', { total })
2385
+ }
2386
+ if (sessions.length === 0) {
2387
+ const empty = document.createElement('div')
2388
+ empty.className = 'session-empty'
2389
+ empty.textContent = query.length > 0
2390
+ ? t('没有匹配的会话。')
2391
+ : archivedOnly()
2392
+ ? t('还没有归档的会话。')
2393
+ : archivedCount() > 0
2394
+ ? t('没有活跃会话。打开视图选项查看归档。')
2395
+ : t('还没有会话。点「新建」开始。')
2396
+ el.sessionList.append(empty)
2397
+ updateListMore()
2398
+ return
2399
+ }
2400
+ if (grouped) {
2401
+ for (const group of sessionGroups(sessions)) {
2402
+ el.sessionList.append(sessionGroupHeader(group))
2403
+ if (state.collapsedGroups.has(group.key)) continue
2404
+ const watermark = groupWatermark(group)
2405
+ const visible = group.sessions.slice(0, watermark)
2406
+ for (const session of visible) el.sessionList.append(sessionRow(session, { showWorkspace: false }))
2407
+ if (group.sessions.length > watermark || watermark > groupBaseline(group)) {
2408
+ el.sessionList.append(groupMoreButton(group))
2409
+ }
2410
+ }
2411
+ } else {
2412
+ for (const session of [...sessions].sort(compareSessionRows)) {
2413
+ el.sessionList.append(sessionRow(session, { showWorkspace: true }))
2414
+ }
2415
+ }
2416
+ updateListMore()
2417
+ }
2418
+
2419
+ function sessionRow(session, options = {}) {
2420
+ const archived = session.archived === true || archivedOnly()
2421
+ const row = document.createElement('div')
2422
+ row.className = `session-row${session.id === state.sessionId ? ' active' : ''}${session.pinned === true ? ' pinned' : ''}${archived ? ' archived' : ''}`
2423
+ row.dataset.id = session.id
2424
+
2425
+ const open = document.createElement('button')
2426
+ open.type = 'button'
2427
+ open.className = 'session-open'
2428
+ open.setAttribute('aria-label', t('打开会话 {title}', { title: session.title }))
2429
+ open.addEventListener('click', () => openSession(session.id))
2430
+
2431
+ const avatar = document.createElement('span')
2432
+ avatar.className = 'session-avatar'
2433
+ avatar.dataset.tone = String(sessionTone(session.id))
2434
+ avatar.textContent = firstGlyph(session.title)
2435
+ avatar.setAttribute('aria-hidden', 'true')
2436
+ const status = document.createElement('span')
2437
+ status.className = `session-status${session.running ? ' running' : session.live ? ' live' : ''}`
2438
+ avatar.append(status)
2439
+
2440
+ const body = document.createElement('span')
2441
+ body.className = 'session-body'
2442
+ const titleRow = document.createElement('span')
2443
+ titleRow.className = 'session-title-row'
2444
+ const name = document.createElement('span')
2445
+ name.className = 'session-name'
2446
+ name.textContent = session.title
2447
+ name.title = session.title
2448
+ const time = document.createElement('span')
2449
+ time.className = 'session-time'
2450
+ time.textContent = relativeTime(session.updatedAt)
2451
+ titleRow.append(name, time)
2452
+
2453
+ const meta = document.createElement('span')
2454
+ meta.className = 'session-meta'
2455
+ const bits = []
2456
+ const workspace = sessionWorkspace(session)
2457
+ if (options.showWorkspace === true) {
2458
+ if (workspace !== null) bits.push(workspace.title)
2459
+ else if (session.cwd) bits.push(shortPath(session.cwd))
2460
+ else bits.push(t('未分组'))
2461
+ } else if (workspace === null && session.cwd) {
2462
+ bits.push(shortPath(session.cwd))
2463
+ }
2464
+ if (session.pinned === true) bits.push(t('置顶'))
2465
+ if (archived) bits.push(t('已归档'))
2466
+ else if (session.running) bits.push(t('运行中'))
2467
+ meta.textContent = bits.join(' · ')
2468
+ body.append(titleRow, meta)
2469
+ open.append(avatar, body)
2470
+
2471
+ const more = document.createElement('button')
2472
+ more.type = 'button'
2473
+ more.className = 'session-more'
2474
+ more.textContent = '⋯'
2475
+ more.setAttribute('aria-label', t('会话设置'))
2476
+ more.setAttribute('aria-haspopup', 'dialog')
2477
+ more.addEventListener('click', (event) => {
2478
+ event.preventDefault()
2479
+ event.stopPropagation()
2480
+ void openSessionActions(session)
2481
+ })
2482
+
2483
+ row.append(open)
2484
+ if (Number.isInteger(state.bootstrap?.archivedCount)) row.append(more)
2485
+ return row
2486
+ }
2487
+
2488
+ function resetSearch() {
2489
+ if (state.searchTimer !== null) {
2490
+ clearTimeout(state.searchTimer)
2491
+ state.searchTimer = null
2492
+ }
2493
+ state.searchToken += 1
2494
+ state.sessionFilter = ''
2495
+ el.sessionSearch.value = ''
2496
+ state.searchRows = []
2497
+ state.searchTotal = 0
2498
+ state.searchHasMore = false
2499
+ state.searchLoading = false
2500
+ state.searchQuery = ''
2501
+ state.searchScope = ''
2502
+ state.searchOffsets = { active: 0, archived: 0 }
2503
+ }
2504
+
2505
+ function searchHaystack(row) {
2506
+ const workspace = sessionWorkspace(row)
2507
+ return `${row.title ?? ''}\n${row.cwd ?? ''}\n${workspace?.title ?? ''}`.toLowerCase()
2508
+ }
2509
+
2510
+ function searchSource() {
2511
+ if (archivedOnly()) return state.archived
2512
+ const active = activeSessions()
2513
+ return archivedVisible() ? mergeSessionRows(active, state.archived) : active
2514
+ }
2515
+
2516
+ function onSearchInput() {
2517
+ const value = el.sessionSearch.value
2518
+ state.sessionFilter = value
2519
+ const query = value.trim()
2520
+ if (state.searchTimer !== null) {
2521
+ clearTimeout(state.searchTimer)
2522
+ state.searchTimer = null
2523
+ }
2524
+ state.searchToken += 1
2525
+ if (query.length === 0) {
2526
+ state.searchRows = []
2527
+ state.searchTotal = 0
2528
+ state.searchHasMore = false
2529
+ state.searchLoading = false
2530
+ state.searchQuery = ''
2531
+ state.searchScope = ''
2532
+ state.searchOffsets = { active: 0, archived: 0 }
2533
+ renderSessionList()
2534
+ return
2535
+ }
2536
+ state.searchQuery = query
2537
+ state.searchScope = searchScopes().join('+')
2538
+ state.searchOffsets = { active: 0, archived: 0 }
2539
+ state.searchRows = []
2540
+ state.searchTotal = 0
2541
+ state.searchHasMore = false
2542
+ state.searchLoading = true
2543
+ renderSessionList()
2544
+ state.searchTimer = setTimeout(() => {
2545
+ state.searchTimer = null
2546
+ void runSearch(false)
2547
+ }, 280)
2548
+ }
2549
+
2550
+ async function runSearch(append) {
2551
+ const query = filterQuery()
2552
+ if (query.length === 0) return
2553
+ if (!state.pagedSearch) {
2554
+ const lowered = query.toLowerCase()
2555
+ state.searchRows = searchSource().filter((row) => searchHaystack(row).includes(lowered))
2556
+ state.searchTotal = state.searchRows.length
2557
+ state.searchHasMore = false
2558
+ state.searchLoading = false
2559
+ renderSessionList()
2560
+ return
2561
+ }
2562
+ if (append && (!state.searchHasMore || state.searchLoading)) return
2563
+ const scopes = searchScopes()
2564
+ const token = ++state.searchToken
2565
+ state.searchLoading = true
2566
+ state.searchQuery = query
2567
+ state.searchScope = scopes.join('+')
2568
+ if (!append) {
2569
+ state.searchRows = []
2570
+ state.searchTotal = 0
2571
+ state.searchHasMore = false
2572
+ state.searchOffsets = { active: 0, archived: 0 }
2573
+ }
2574
+ renderSessionList()
2575
+ const offsets = { ...state.searchOffsets }
2576
+ try {
2577
+ const pages = await Promise.all(scopes.map((scope) =>
2578
+ api(`${API.sessions}?scope=${scope}&offset=${offsets[scope] ?? 0}&q=${encodeURIComponent(query)}`)))
2579
+ if (token !== state.searchToken) return
2580
+ const rows = []
2581
+ let total = 0
2582
+ let hasMore = false
2583
+ let archivedCount = null
2584
+ for (const [index, data] of pages.entries()) {
2585
+ const scope = scopes[index]
2586
+ const page = Array.isArray(data.sessions) ? data.sessions : []
2587
+ rows.push(...page)
2588
+ state.searchOffsets[scope] = (offsets[scope] ?? 0) + page.length
2589
+ total += Number.isInteger(data.total) ? data.total : page.length
2590
+ hasMore = hasMore || data.hasMore === true
2591
+ if (Number.isInteger(data.archivedCount)) archivedCount = data.archivedCount
2592
+ }
2593
+ // Hosts released before Workspace-aware search only match title/cwd.
2594
+ // Supplement the page with rows this view already knows whose folder
2595
+ // label matches, so folder search still works before a restart.
2596
+ const lowered = query.toLowerCase()
2597
+ const localMatches = searchSource().filter((row) => searchHaystack(row).includes(lowered))
2598
+ state.searchRows = mergeSessionRows(append ? state.searchRows : [], rows, localMatches)
2599
+ state.searchTotal = Math.max(total, state.searchRows.length)
2600
+ state.searchHasMore = hasMore
2601
+ if (archivedCount !== null && state.bootstrap !== null) {
2602
+ state.bootstrap.archivedCount = archivedCount
2603
+ }
2604
+ } catch (error) {
2605
+ if (token !== state.searchToken) return
2606
+ if (error instanceof ApiError && error.code === 'http-404') {
2607
+ // Older backends lack the paged endpoint; keep search useful over the rows
2608
+ // this view has already loaded instead of failing outright.
2609
+ const lowered = query.toLowerCase()
2610
+ state.searchRows = searchSource().filter((row) => searchHaystack(row).includes(lowered))
2611
+ state.searchTotal = state.searchRows.length
2612
+ state.searchHasMore = false
2613
+ } else {
2614
+ handleError(error)
2615
+ }
2616
+ } finally {
2617
+ if (token === state.searchToken) {
2618
+ state.searchLoading = false
2619
+ renderSessionList()
2620
+ }
2621
+ }
2622
+ }
2623
+
2624
+ async function loadArchivedSessions(force = false, options = {}) {
2625
+ const append = options.append === true
2626
+ if (state.archivedLoading) return
2627
+ if (append && !state.archivedHasMore) return
2628
+ if (!append && !force && state.archivedLoadedAt > 0 && Date.now() - state.archivedLoadedAt < 30_000) return
2629
+ state.archivedLoading = true
2630
+ const token = ++state.archivedToken
2631
+ if (!append) state.archivedLoadedAt = 0
2632
+ renderSessionList()
2633
+ try {
2634
+ const offset = append ? state.archived.length : 0
2635
+ const data = await api(`${API.archived}?offset=${offset}`)
2636
+ if (token !== state.archivedToken) return
2637
+ const rows = Array.isArray(data.sessions) ? data.sessions : []
2638
+ state.archived = append ? mergeSessionRows(state.archived, rows) : rows
2639
+ state.archivedTotal = Number.isInteger(data.total) ? data.total : state.archived.length
2640
+ state.archivedHasMore = data.hasMore === true
2641
+ if (Number.isInteger(data.archivedCount) && state.bootstrap !== null) {
2642
+ state.bootstrap.archivedCount = data.archivedCount
2643
+ }
2644
+ state.archivedLoadedAt = Date.now()
2645
+ } catch (error) {
2646
+ if (token === state.archivedToken) handleError(error)
2647
+ } finally {
2648
+ if (token === state.archivedToken) {
2649
+ state.archivedLoading = false
2650
+ renderSessionList()
2651
+ }
2652
+ }
2653
+ }
2654
+
2655
+ async function loadActiveMore() {
2656
+ if (state.activeLoadingMore || !state.activeHasMore) return
2657
+ state.activeLoadingMore = true
2658
+ const token = ++state.activeToken
2659
+ renderSessionList()
2660
+ try {
2661
+ const offset = activeSessions().length
2662
+ const data = await api(`${API.sessions}?scope=active&offset=${offset}`)
2663
+ if (token !== state.activeToken) return
2664
+ const rows = Array.isArray(data.sessions) ? data.sessions : []
2665
+ state.activeExtra = mergeSessionRows(state.activeExtra, rows)
2666
+ state.activeTotal = Number.isInteger(data.total) ? data.total : offset + rows.length
2667
+ state.activeHasMore = data.hasMore === true
2668
+ } catch (error) {
2669
+ if (token === state.activeToken) handleError(error)
2670
+ } finally {
2671
+ if (token === state.activeToken) {
2672
+ state.activeLoadingMore = false
2673
+ renderSessionList()
2674
+ }
2675
+ }
2676
+ }
2677
+
2678
+ function loadMoreSessions() {
2679
+ if (searching()) void runSearch(true)
2680
+ else if (archivedOnly()) void loadArchivedSessions(true, { append: true })
2681
+ else if (archivedVisible()) {
2682
+ if (state.activeHasMore) void loadActiveMore()
2683
+ else void loadArchivedSessions(true, { append: true })
2684
+ } else void loadActiveMore()
2685
+ }
2686
+
2687
+ async function openSessionActions(session) {
2688
+ const archived = session.archived === true || archivedOnly()
2689
+ const action = await showDialog({
2690
+ title: t('会话设置'),
2691
+ message: session.title,
2692
+ vertical: true,
2693
+ actions: [
2694
+ { label: t('运行信息'), value: 'insights' },
2695
+ { label: t('权限模式'), value: 'permissions' },
2696
+ { label: t('重命名'), value: 'rename' },
2697
+ { label: t('分叉会话'), value: 'fork' },
2698
+ { label: t('复制 Markdown'), value: 'copy' },
2699
+ { label: t('导出 ZIP'), value: 'export' },
2700
+ ...archived
2701
+ ? []
2702
+ : [{ label: session.pinned === true ? t('取消置顶') : t('置顶会话'), value: 'pin' }],
2703
+ archived
2704
+ ? { label: t('恢复到活跃会话'), value: 'unarchive' }
2705
+ : { label: t('归档会话'), value: 'archive', danger: true },
2706
+ { label: t('取消'), value: null, cancel: true },
2707
+ ],
2708
+ })
2709
+ if (action === 'insights') await showInsights(session.id)
2710
+ else if (action === 'permissions') await changePermissions(session)
2711
+ else if (action === 'rename') await renameSession(session)
2712
+ else if (action === 'fork') await forkSession(session)
2713
+ else if (action === 'copy') await copyMarkdown(session)
2714
+ else if (action === 'export') downloadExport(session)
2715
+ else if (action === 'pin') await togglePin(session)
2716
+ else if (action === 'archive') await archiveSession(session)
2717
+ else if (action === 'unarchive') await unarchiveSession(session)
2718
+ }
2719
+
2720
+ async function renameSession(session) {
2721
+ const value = await showDialog({
2722
+ title: t('重命名会话'),
2723
+ message: t('标题会立即同步到完整页面。'),
2724
+ input: true,
2725
+ value: session.title,
2726
+ placeholder: t('输入新的会话标题'),
2727
+ confirmText: t('保存'),
2728
+ cancelText: t('取消'),
2729
+ })
2730
+ if (value === null) return
2731
+ const title = value.trim()
2732
+ if (title.length === 0 || title === session.title) return
2733
+ try {
2734
+ const data = await post(API.rename, { sessionId: session.id, title })
2735
+ const accepted = typeof data.title === 'string' ? data.title : title
2736
+ session.title = accepted
2737
+ const active = state.bootstrap?.sessions.find((row) => row.id === session.id)
2738
+ if (active !== undefined) active.title = accepted
2739
+ const archived = state.archived.find((row) => row.id === session.id)
2740
+ if (archived !== undefined) archived.title = accepted
2741
+ if (state.session?.id === session.id) {
2742
+ state.session.title = accepted
2743
+ el.title.textContent = accepted
2744
+ }
2745
+ if (state.bootstrap !== null) cacheBootstrap(state.bootstrap)
2746
+ renderSessionList()
2747
+ showBanner(t('已重命名'), false, 'ok')
2748
+ } catch (error) {
2749
+ handleError(error)
2750
+ }
2751
+ }
2752
+
2753
+ async function forkSession(session) {
2754
+ showBanner(t('正在分叉会话…'), true)
2755
+ try {
2756
+ const data = await post(API.fork, { sessionId: session.id })
2757
+ await loadBootstrap(true)
2758
+ if (typeof data.sessionId === 'string' && data.sessionId.length > 0) openSession(data.sessionId)
2759
+ clearBanner()
2760
+ showBanner(t('已分叉为新会话'), false, 'ok')
2761
+ } catch (error) {
2762
+ clearBanner()
2763
+ handleError(error)
2764
+ }
2765
+ }
2766
+
2767
+ async function copyMarkdown(session) {
2768
+ showBanner(t('正在准备 Markdown…'), true)
2769
+ try {
2770
+ const response = await fetch(`/api/session.markdown?sessionId=${encodeURIComponent(session.id)}`, {
2771
+ headers: { accept: 'text/markdown' },
2772
+ })
2773
+ if (!response.ok) {
2774
+ throw new Error(response.status === 404 ? t('会话不存在') : t('宿主未启用 Markdown 导出'))
2775
+ }
2776
+ await copyText(await response.text())
2777
+ clearBanner()
2778
+ showBanner(t('已复制 Markdown'), false, 'ok')
2779
+ } catch (error) {
2780
+ clearBanner()
2781
+ handleError(error)
2782
+ }
2783
+ }
2784
+
2785
+ function downloadExport(session) {
2786
+ const url = `/api/session.export?sessionId=${encodeURIComponent(session.id)}&includeDescendants=true`
2787
+ const link = document.createElement('a')
2788
+ link.href = url
2789
+ link.download = `dsh-session-${session.id}.zip`
2790
+ link.rel = 'noopener'
2791
+ document.body.append(link)
2792
+ link.click()
2793
+ link.remove()
2794
+ showBanner(t('已开始导出会话'), false, 'ok')
2795
+ }
2796
+
2797
+ function compareSessions(left, right) {
2798
+ return Number(right.pinned === true) - Number(left.pinned === true) ||
2799
+ (right.updatedAt ?? 0) - (left.updatedAt ?? 0)
2800
+ }
2801
+
2802
+ async function togglePin(session) {
2803
+ const pinned = session.pinned !== true
2804
+ try {
2805
+ await post(API.pin, { sessionId: session.id, pinned })
2806
+ session.pinned = pinned
2807
+ const active = state.bootstrap?.sessions.find((row) => row.id === session.id)
2808
+ if (active !== undefined) active.pinned = pinned
2809
+ if (state.session?.id === session.id) state.session.pinned = pinned
2810
+ if (state.bootstrap !== null) {
2811
+ state.bootstrap.sessions.sort(compareSessions)
2812
+ cacheBootstrap(state.bootstrap)
2813
+ }
2814
+ renderSessionList()
2815
+ showBanner(pinned ? t('已置顶') : t('已取消置顶'), false, 'ok')
2816
+ } catch (error) {
2817
+ handleError(error)
2818
+ }
2819
+ }
2820
+
2821
+ async function archiveSession(session) {
2822
+ const confirmed = await showDialog({
2823
+ title: t('归档会话'),
2824
+ message: session.running
2825
+ ? t('该会话正在运行。归档会先停止当前回合,之后可在「仅归档」中恢复。')
2826
+ : t('归档后可在「仅归档」中随时恢复。'),
2827
+ confirmText: t('归档'),
2828
+ cancelText: t('取消'),
2829
+ danger: true,
2830
+ })
2831
+ if (confirmed !== true) return
2832
+ try {
2833
+ await post(API.archive, {
2834
+ sessionId: session.id,
2835
+ ...session.running === true ? { stopActivity: true } : {},
2836
+ })
2837
+ await afterArchiveChange(session.id)
2838
+ showBanner(t('已归档'), false, 'ok')
2839
+ } catch (error) {
2840
+ if (error instanceof ApiError && error.code === 'workspace/session-active') {
2841
+ const stop = await showDialog({
2842
+ title: t('会话正在运行'),
2843
+ message: t('归档会停止当前回合和它启动的后台任务。继续吗?'),
2844
+ confirmText: t('停止并归档'),
2845
+ cancelText: t('取消'),
2846
+ danger: true,
2847
+ })
2848
+ if (stop !== true) return
2849
+ try {
2850
+ await post(API.archive, { sessionId: session.id, stopActivity: true })
2851
+ await afterArchiveChange(session.id)
2852
+ showBanner(t('已归档'), false, 'ok')
2853
+ } catch (next) {
2854
+ handleError(next)
2855
+ }
2856
+ return
2857
+ }
2858
+ handleError(error)
2859
+ }
2860
+ }
2861
+
2862
+ async function unarchiveSession(session) {
2863
+ try {
2864
+ await post(API.unarchive, { sessionId: session.id })
2865
+ state.archived = state.archived.filter((row) => row.id !== session.id)
2866
+ state.archivedTotal = Math.max(0, state.archivedTotal - 1)
2867
+ state.archivedLoadedAt = Date.now()
2868
+ await loadBootstrap(true)
2869
+ if (archivedVisible()) {
2870
+ if (searching()) await runSearch(false)
2871
+ else if (archivedOnly()) {
2872
+ if (state.archived.length === 0) setArchivedFilter('hide')
2873
+ else await loadArchivedSessions(true)
2874
+ }
2875
+ }
2876
+ if (state.sessionId === session.id) void loadSession()
2877
+ renderSessionList()
2878
+ showBanner(t('已恢复'), false, 'ok')
2879
+ } catch (error) {
2880
+ handleError(error)
2881
+ }
2882
+ }
2883
+
2884
+ async function afterArchiveChange(archivedId) {
2885
+ state.archivedLoadedAt = 0
2886
+ state.archived = state.archived.filter((row) => row.id !== archivedId)
2887
+ state.archivedTotal += 1
2888
+ state.searchRows = state.searchRows.filter((row) => row.id !== archivedId)
2889
+ state.searchHasMore = false
2890
+ const currentRemoved = state.sessionId === archivedId
2891
+ const refreshed = await loadBootstrap(true)
2892
+ if (currentRemoved && state.bootstrap !== null) {
2893
+ // Even if the refresh failed, do not reopen the session we just archived.
2894
+ state.bootstrap.sessions = state.bootstrap.sessions.filter((row) => row.id !== archivedId)
2895
+ if (refreshed === null) {
2896
+ state.bootstrap.archivedCount = (Number.isInteger(state.bootstrap.archivedCount) ? state.bootstrap.archivedCount : 0) + 1
2897
+ }
2898
+ }
2899
+ if (archivedVisible()) {
2900
+ if (searching()) await runSearch(false)
2901
+ else await loadArchivedSessions(true)
2902
+ }
2903
+ if (currentRemoved) {
2904
+ saveCurrentDraft()
2905
+ clearSession()
2906
+ const next = state.bootstrap?.sessions?.[0]
2907
+ if (next !== undefined) openSession(next.id)
2908
+ else renderEmpty(t('没有活跃会话。打开视图选项查看已归档会话。'))
2909
+ }
2910
+ renderSessionList()
2911
+ }
2912
+
2913
+ function clearSession() {
2914
+ state.pollToken += 1
2915
+ if (state.timer !== null) {
2916
+ clearTimeout(state.timer)
2917
+ state.timer = null
2918
+ }
2919
+ state.sessionId = null
2920
+ state.session = null
2921
+ state.sessionCursor = null
2922
+ state.history = []
2923
+ state.historyCursor = null
2924
+ state.historyHasMore = true
2925
+ state.historyInitialized = false
2926
+ state.queueEditingId = null
2927
+ state.queueDraft = ''
2928
+ state.queueSignature = ''
2929
+ state.commands = null
2930
+ state.commandsSessionId = null
2931
+ state.messageSignature = ''
2932
+ try {
2933
+ localStorage.removeItem(STORAGE.session)
2934
+ } catch {
2935
+ // Non-fatal.
2936
+ }
2937
+ restoreDraft()
2938
+ renderIdle()
2939
+ }
2940
+
2941
+ function showDialog(options) {
2942
+ return new Promise((resolve) => {
2943
+ if (state.dialogResolve !== null) closeDialog(null)
2944
+ state.dialogResolve = resolve
2945
+ state.dialogLastFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null
2946
+ el.dialogTitle.textContent = options.title ?? ''
2947
+ const message = options.message ?? ''
2948
+ el.dialogMessage.textContent = message
2949
+ el.dialogMessage.dataset.kind = options.detail === true ? 'details' : 'text'
2950
+ el.dialogMessage.hidden = message.length === 0
2951
+ const hasInput = options.input === true
2952
+ el.dialogInput.hidden = !hasInput
2953
+ el.dialogInput.value = hasInput ? String(options.value ?? '') : ''
2954
+ el.dialogInput.placeholder = options.placeholder ?? ''
2955
+ el.dialogActions.replaceChildren()
2956
+ const actions = Array.isArray(options.actions) ? options.actions : [
2957
+ { label: options.cancelText ?? t('取消'), value: null, cancel: true },
2958
+ { label: options.confirmText ?? t('确定'), value: true, primary: true, danger: options.danger === true },
2959
+ ]
2960
+ const vertical = Array.isArray(options.actions) || options.vertical === true
2961
+ el.dialogActions.dataset.layout = vertical ? 'stack' : 'row'
2962
+ for (const action of actions) {
2963
+ const button = document.createElement('button')
2964
+ button.type = 'button'
2965
+ button.className = `dialog-action${action.primary ? ' primary' : ''}${action.danger ? ' danger' : ''}${action.cancel ? ' cancel' : ''}`
2966
+ button.textContent = action.label
2967
+ button.addEventListener('click', () => {
2968
+ const value = action.cancel === true || action.value === null
2969
+ ? null
2970
+ : hasInput
2971
+ ? el.dialogInput.value
2972
+ : action.value
2973
+ closeDialog(value)
2974
+ })
2975
+ el.dialogActions.append(button)
2976
+ }
2977
+ el.dialog.hidden = false
2978
+ document.body.classList.add('dialog-open')
2979
+ requestAnimationFrame(() => {
2980
+ if (hasInput) {
2981
+ el.dialogInput.focus()
2982
+ el.dialogInput.select()
2983
+ } else {
2984
+ el.dialogActions.querySelector('button')?.focus()
2985
+ }
2986
+ })
2987
+ })
2988
+ }
2989
+
2990
+ function closeDialog(value) {
2991
+ if (state.dialogResolve === null) return
2992
+ const resolve = state.dialogResolve
2993
+ state.dialogResolve = null
2994
+ el.dialog.hidden = true
2995
+ document.body.classList.remove('dialog-open')
2996
+ const previous = state.dialogLastFocus
2997
+ state.dialogLastFocus = null
2998
+ if (previous !== null) previous.focus({ preventScroll: true })
2999
+ resolve(value)
3000
+ }
3001
+
3002
+
3003
+ function renderModelOptions() {
3004
+ const models = state.bootstrap?.models
3005
+ if (!models || !Array.isArray(models.groups)) return
3006
+ const signature = models.groups.map((group) => `${group.id}:${group.models.map((model) => model.id).join(',')}`).join('|')
3007
+ if (signature === state.modelSignature) return
3008
+ state.modelSignature = signature
3009
+ el.modelSelect.replaceChildren()
3010
+ for (const group of models.groups) {
3011
+ const optgroup = document.createElement('optgroup')
3012
+ optgroup.label = group.name || group.id
3013
+ for (const model of group.models) {
3014
+ const option = document.createElement('option')
3015
+ option.value = `${group.id}\u0000${model.id}`
3016
+ option.textContent = model.name || model.id
3017
+ optgroup.append(option)
3018
+ }
3019
+ if (optgroup.children.length > 0) el.modelSelect.append(optgroup)
3020
+ }
3021
+ if (el.modelSelect.children.length === 0) {
3022
+ const option = document.createElement('option')
3023
+ option.value = ''
3024
+ option.textContent = t('无可用模型')
3025
+ el.modelSelect.append(option)
3026
+ }
3027
+ }
3028
+
3029
+ function renderPresets() {
3030
+ const presets = Array.isArray(state.bootstrap?.presets) ? state.bootstrap.presets : []
3031
+ const usable = presets.filter((preset) => typeof preset.id === 'string' && preset.id.length > 0)
3032
+ if (usable.length <= 1) {
3033
+ el.presetBar.hidden = true
3034
+ el.presetSelect.replaceChildren()
3035
+ el.presetSelect.dataset.signature = ''
3036
+ return
3037
+ }
3038
+ el.presetBar.hidden = false
3039
+ const signature = usable.map((preset) => `${preset.id}:${preset.name ?? ''}:${preset.broken ?? ''}`).join('|')
3040
+ if (el.presetSelect.dataset.signature !== signature) {
3041
+ el.presetSelect.dataset.signature = signature
3042
+ el.presetSelect.replaceChildren()
3043
+ for (const preset of usable) {
3044
+ const option = document.createElement('option')
3045
+ option.value = preset.id
3046
+ const broken = typeof preset.broken === 'string' && preset.broken.length > 0
3047
+ const name = preset.name || preset.id
3048
+ option.textContent = `${preset.isDefault ? t('{name}(默认)', { name }) : name}${broken ? t('(不可用)') : ''}`
3049
+ option.disabled = broken
3050
+ el.presetSelect.append(option)
3051
+ }
3052
+ }
3053
+ const saved = savedPresetId()
3054
+ const fallback = usable.find((preset) => preset.isDefault === true)?.id ?? usable[0].id
3055
+ const selected = usable.some((preset) => preset.id === saved) ? saved : fallback
3056
+ if (el.presetSelect.value !== selected) el.presetSelect.value = selected
3057
+ }
3058
+
3059
+ function renderWorkspaces() {
3060
+ const workspaces = Array.isArray(state.bootstrap?.workspaces) ? state.bootstrap.workspaces : []
3061
+ const usable = workspaces.filter((workspace) => typeof workspace.id === 'string' && workspace.id.length > 0)
3062
+ if (usable.length === 0) {
3063
+ el.workspaceBar.hidden = true
3064
+ el.workspaceSelect.replaceChildren()
3065
+ el.workspaceSelect.dataset.signature = ''
3066
+ return
3067
+ }
3068
+ el.workspaceBar.hidden = false
3069
+ const signature = usable.map((workspace) => `${workspace.id}:${workspace.title ?? ''}:${workspace.path ?? ''}`).join('|')
3070
+ const previous = el.workspaceSelect.value
3071
+ if (el.workspaceSelect.dataset.signature !== signature) {
3072
+ el.workspaceSelect.dataset.signature = signature
3073
+ el.workspaceSelect.replaceChildren()
3074
+ const auto = document.createElement('option')
3075
+ auto.value = ''
3076
+ auto.textContent = t('自动(默认位置)')
3077
+ el.workspaceSelect.append(auto)
3078
+ for (const workspace of usable) {
3079
+ const option = document.createElement('option')
3080
+ option.value = workspace.id
3081
+ option.textContent = workspace.title || workspace.path || workspace.id
3082
+ if (typeof workspace.path === 'string') option.title = workspace.path
3083
+ el.workspaceSelect.append(option)
3084
+ }
3085
+ const custom = document.createElement('option')
3086
+ custom.value = '__custom__'
3087
+ custom.textContent = t('自定义目录…')
3088
+ el.workspaceSelect.append(custom)
3089
+ }
3090
+ const selected = usable.some((workspace) => workspace.id === previous) ? previous : ''
3091
+ if (el.workspaceSelect.value !== selected) el.workspaceSelect.value = selected
3092
+ }
3093
+
3094
+ function syncModelSelect(model) {
3095
+ if (!model || typeof model.provider !== 'string' || typeof model.model !== 'string') return
3096
+ const value = `${model.provider}\u0000${model.model}`
3097
+ const existing = [...el.modelSelect.options].some((option) => option.value === value)
3098
+ if (!existing) {
3099
+ const option = document.createElement('option')
3100
+ option.value = value
3101
+ option.textContent = `${model.provider}/${model.model}`
3102
+ el.modelSelect.append(option)
3103
+ }
3104
+ if (el.modelSelect.value !== value) el.modelSelect.value = value
3105
+ }
3106
+
3107
+ function catalogModel(provider, model) {
3108
+ const groups = state.bootstrap?.models?.groups
3109
+ if (!Array.isArray(groups)) return null
3110
+ for (const group of groups) {
3111
+ if (group.id !== provider) continue
3112
+ for (const item of Array.isArray(group.models) ? group.models : []) {
3113
+ if (item.id === model) return item
3114
+ }
3115
+ }
3116
+ return null
3117
+ }
3118
+
3119
+ function syncEffort(model) {
3120
+ const descriptor = model ? catalogModel(model.provider, model.model) : null
3121
+ const reasoning = descriptor?.reasoning
3122
+ const efforts = Array.isArray(reasoning?.efforts) ? reasoning.efforts : []
3123
+ if (efforts.length === 0) {
3124
+ el.effortSelect.hidden = true
3125
+ if (el.effortSelect.dataset.signature !== '') {
3126
+ el.effortSelect.replaceChildren()
3127
+ el.effortSelect.dataset.signature = ''
3128
+ }
3129
+ return
3130
+ }
3131
+ el.effortSelect.hidden = false
3132
+ el.effortSelect.title = t('思考强度')
3133
+ const signature = efforts.map((effort) => `${effort.id}:${effort.name}`).join('|')
3134
+ if (el.effortSelect.dataset.signature !== signature) {
3135
+ el.effortSelect.dataset.signature = signature
3136
+ el.effortSelect.replaceChildren()
3137
+ for (const effort of efforts) {
3138
+ const option = document.createElement('option')
3139
+ option.value = effort.id
3140
+ option.textContent = effort.name || effort.id
3141
+ el.effortSelect.append(option)
3142
+ }
3143
+ }
3144
+ const current = typeof model?.reasoningEffort === 'string'
3145
+ ? model.reasoningEffort
3146
+ : typeof reasoning.defaultEffort === 'string'
3147
+ ? reasoning.defaultEffort
3148
+ : efforts[0].id
3149
+ if (el.effortSelect.value !== current) el.effortSelect.value = current
3150
+ }
3151
+
3152
+ async function selectModel() {
3153
+ const session = state.session
3154
+ const value = el.modelSelect.value
3155
+ if (session === null || value === '') return
3156
+ const [provider, model] = value.split('\u0000')
3157
+ if (!provider || !model) return
3158
+ const effort = el.effortSelect.hidden ? undefined : el.effortSelect.value || undefined
3159
+ const unchanged = session.model &&
3160
+ session.model.provider === provider &&
3161
+ session.model.model === model &&
3162
+ (session.model.reasoningEffort ?? undefined) === effort
3163
+ if (unchanged) return
3164
+ el.modelStatus.textContent = t('切换中…')
3165
+ try {
3166
+ const data = await post(API.model, {
3167
+ sessionId: session.id,
3168
+ provider,
3169
+ model,
3170
+ ...(effort === undefined ? {} : { reasoningEffort: effort }),
3171
+ })
3172
+ session.model = data.selected ?? { provider, model, ...(effort === undefined ? {} : { reasoningEffort: effort }) }
3173
+ renderSession()
3174
+ el.modelStatus.textContent = t('已切换')
3175
+ setTimeout(() => {
3176
+ if (el.modelStatus.textContent === t('已切换')) el.modelStatus.textContent = ''
3177
+ }, 2500)
3178
+ } catch (error) {
3179
+ el.modelStatus.textContent = ''
3180
+ showBanner(error instanceof Error ? error.message : String(error))
3181
+ if (session.model) {
3182
+ syncModelSelect(session.model)
3183
+ syncEffort(session.model)
3184
+ }
3185
+ }
3186
+ }
3187
+
3188
+ async function refreshModels() {
3189
+ if (state.modelRefreshing) return
3190
+ state.modelRefreshing = true
3191
+ el.modelRefresh.disabled = true
3192
+ el.modelStatus.textContent = t('刷新中…')
3193
+ try {
3194
+ const data = await loadBootstrap(true)
3195
+ if (data === null) {
3196
+ el.modelStatus.textContent = ''
3197
+ return
3198
+ }
3199
+ el.modelStatus.textContent = t('已刷新')
3200
+ setTimeout(() => {
3201
+ if (el.modelStatus.textContent === t('已刷新')) el.modelStatus.textContent = ''
3202
+ }, 2200)
3203
+ } finally {
3204
+ state.modelRefreshing = false
3205
+ el.modelRefresh.disabled = false
3206
+ }
3207
+ }
3208
+
3209
+ function hideCommandMenu() {
3210
+ state.commandMenuToken += 1
3211
+ el.commandMenu.hidden = true
3212
+ el.commandMenuList.replaceChildren()
3213
+ }
3214
+
3215
+ function showCommandMenu(commands) {
3216
+ el.commandMenuList.replaceChildren()
3217
+ if (commands.length === 0) {
3218
+ el.commandMenu.hidden = true
3219
+ return
3220
+ }
3221
+ for (const command of commands) {
3222
+ const row = document.createElement('button')
3223
+ row.type = 'button'
3224
+ row.className = 'command-item'
3225
+ const name = document.createElement('span')
3226
+ name.className = 'command-name'
3227
+ name.textContent = `/${command.name}`
3228
+ const detail = document.createElement('span')
3229
+ detail.className = 'command-desc'
3230
+ detail.textContent = command.description || command.hint || ''
3231
+ row.append(name, detail)
3232
+ row.addEventListener('pointerdown', (event) => {
3233
+ event.preventDefault()
3234
+ el.prompt.value = `/${command.name} `
3235
+ el.prompt.focus()
3236
+ resizePrompt()
3237
+ hideCommandMenu()
3238
+ })
3239
+ el.commandMenuList.append(row)
3240
+ }
3241
+ el.commandMenu.hidden = false
3242
+ }
3243
+
3244
+ async function ensureCommands(force = false) {
3245
+ const id = state.sessionId
3246
+ if (id === null) return []
3247
+ if (
3248
+ !force &&
3249
+ state.commands !== null &&
3250
+ state.commandsSessionId === id &&
3251
+ Date.now() - state.commandsAt < 60_000
3252
+ ) return state.commands
3253
+ try {
3254
+ const data = await api(`${API.commands}?id=${encodeURIComponent(id)}${force ? '&refresh=1' : ''}`)
3255
+ if (state.sessionId !== id) return []
3256
+ state.commands = Array.isArray(data.commands) ? data.commands : []
3257
+ state.commandsSessionId = id
3258
+ state.commandsAt = Date.now()
3259
+ return state.commands
3260
+ } catch (error) {
3261
+ if (isAuthError(error)) handleError(error)
3262
+ return []
3263
+ }
3264
+ }
3265
+
3266
+ async function updateCommandMenu() {
3267
+ const match = /^\/([a-z0-9-]*)$/.exec(el.prompt.value)
3268
+ if (match === null) {
3269
+ hideCommandMenu()
3270
+ return
3271
+ }
3272
+ const token = ++state.commandMenuToken
3273
+ const commands = await ensureCommands()
3274
+ if (token !== state.commandMenuToken) return
3275
+ const prefix = match[1]
3276
+ showCommandMenu(commands.filter((command) => command.name.startsWith(prefix)).slice(0, 8))
3277
+ }
3278
+
3279
+ async function runCommandLine(line) {
3280
+ const result = await post(API.command, { sessionId: state.sessionId, line })
3281
+ if (result.executed !== true) {
3282
+ // The command roster may have changed under us (preset switch, new plugin);
3283
+ // drop the cache and refetch so the next `/` menu is current.
3284
+ state.commands = null
3285
+ void ensureCommands(true)
3286
+ return { ok: false, unknown: true }
3287
+ }
3288
+ if (result.result?.kind === 'error') return { ok: false, text: result.result.text || t('指令执行失败') }
3289
+ return { ok: true }
3290
+ }
3291
+
3292
+ async function sendPrompt() {
3293
+ if (state.sending) return
3294
+ const text = el.prompt.value.trim()
3295
+ const images = state.pendingImages.map((image) => ({
3296
+ mediaType: image.mediaType,
3297
+ data: image.data,
3298
+ ...image.name ? { name: image.name } : {},
3299
+ }))
3300
+ if (text.length === 0 && images.length === 0) return
3301
+ if (images.length > 0 && text.startsWith('/')) {
3302
+ showBanner(t('图片不能随斜杠命令发送;请先移除图片或改为普通消息。'))
3303
+ return
3304
+ }
3305
+ if (state.sessionId === null) {
3306
+ await newSession()
3307
+ if (state.sessionId === null) return
3308
+ }
3309
+ state.sending = true
3310
+ el.send.disabled = true
3311
+ hideCommandMenu()
3312
+ try {
3313
+ if (text.startsWith('/')) {
3314
+ const name = text.split(/\s+/)[0]
3315
+ showBanner(t('正在执行 {name}…', { name }), true)
3316
+ const outcome = await runCommandLine(text)
3317
+ clearBanner()
3318
+ if (outcome.unknown) {
3319
+ showBanner(t('未知或不完整的指令:{name}', { name }))
3320
+ return
3321
+ }
3322
+ if (!outcome.ok) {
3323
+ showBanner(outcome.text || t('指令执行失败'))
3324
+ return
3325
+ }
3326
+ el.prompt.value = ''
3327
+ resizePrompt()
3328
+ clearDraft(state.sessionId)
3329
+ await loadSession()
3330
+ schedulePoll(600)
3331
+ return
3332
+ }
3333
+ await post(API.prompt, {
3334
+ sessionId: state.sessionId,
3335
+ text,
3336
+ ...images.length > 0 ? { images } : {},
3337
+ })
3338
+ el.prompt.value = ''
3339
+ resizePrompt()
3340
+ clearDraft(state.sessionId)
3341
+ clearPendingImages()
3342
+ if (state.session) state.session.running = true
3343
+ renderSession()
3344
+ await loadSession()
3345
+ schedulePoll(600)
3346
+ } catch (error) {
3347
+ handleError(error)
3348
+ } finally {
3349
+ state.sending = false
3350
+ el.send.disabled = state.sessionId === null
3351
+ }
3352
+ }
3353
+
3354
+ async function stopTurn() {
3355
+ if (state.sessionId === null) return
3356
+ try {
3357
+ await post(API.cancel, { sessionId: state.sessionId })
3358
+ el.runningText.textContent = t('正在停止…')
3359
+ schedulePoll(600)
3360
+ } catch (error) {
3361
+ handleError(error)
3362
+ }
3363
+ }
3364
+
3365
+ async function loadEarlier() {
3366
+ const session = state.session
3367
+ if (session === null || state.historyLoading) return
3368
+ const messages = conversationMessages(session)
3369
+ const oldest = messages.find((message) => typeof message.seq === 'number')
3370
+ const beforeSeq = state.historyCursor ?? oldest?.seq ?? null
3371
+ if (beforeSeq === null) return
3372
+ state.historyLoading = true
3373
+ updateHistoryBar()
3374
+ const scroller = el.messages.parentElement
3375
+ const previousHeight = scroller.scrollHeight
3376
+ const previousTop = scroller.scrollTop
3377
+ try {
3378
+ const data = await api(`${API.history}?id=${encodeURIComponent(session.id)}&beforeSeq=${beforeSeq}`)
3379
+ if (state.sessionId !== session.id) return
3380
+ const incoming = Array.isArray(data.messages) ? data.messages : []
3381
+ const known = new Set(messages.map((message) => message.seq).filter((seq) => typeof seq === 'number'))
3382
+ const fresh = incoming.filter((message) => typeof message.seq !== 'number' || !known.has(message.seq))
3383
+ state.history = [...fresh, ...state.history]
3384
+ state.historyCursor = typeof data.nextBeforeSeq === 'number' ? data.nextBeforeSeq : null
3385
+ state.historyHasMore = data.hasMore === true && fresh.length > 0 && state.historyCursor !== null
3386
+ state.messageSignature = ''
3387
+ renderSession()
3388
+ requestAnimationFrame(() => {
3389
+ scroller.scrollTop = previousTop + (scroller.scrollHeight - previousHeight)
3390
+ })
3391
+ } catch (error) {
3392
+ handleError(error)
3393
+ } finally {
3394
+ state.historyLoading = false
3395
+ renderSession()
3396
+ }
3397
+ }
3398
+
3399
+ async function newSession() {
3400
+ try {
3401
+ const preset = el.presetBar.hidden ? undefined : el.presetSelect.value || undefined
3402
+ let workspaceId = el.workspaceBar.hidden ? undefined : el.workspaceSelect.value || undefined
3403
+ let cwd
3404
+ if (workspaceId === '__custom__') {
3405
+ const value = await showDialog({
3406
+ title: t('自定义新会话目录'),
3407
+ message: t('输入一个已存在的绝对路径。'),
3408
+ input: true,
3409
+ placeholder: '/Users/you/project',
3410
+ confirmText: t('使用此目录'),
3411
+ cancelText: t('取消'),
3412
+ })
3413
+ if (value === null) return
3414
+ cwd = value.trim()
3415
+ if (cwd.length === 0) return
3416
+ workspaceId = undefined
3417
+ }
3418
+ const draft = el.prompt.value
3419
+ const images = state.pendingImages
3420
+ const options = {}
3421
+ if (preset !== undefined) options.agentPreset = preset
3422
+ if (workspaceId !== undefined) options.workspaceId = workspaceId
3423
+ if (cwd !== undefined) options.cwd = cwd
3424
+ const data = await post(API.new, options)
3425
+ await loadBootstrap(true)
3426
+ openSession(data.sessionId)
3427
+ if (draft.trim().length > 0) {
3428
+ state.drafts[data.sessionId] = draft.slice(0, MAX_DRAFT_CHARS)
3429
+ delete state.drafts.__new__
3430
+ writeDrafts()
3431
+ el.prompt.value = draft
3432
+ resizePrompt()
3433
+ }
3434
+ if (images.length > 0) {
3435
+ state.pendingImages = images
3436
+ renderImageTray()
3437
+ }
3438
+ el.prompt.focus()
3439
+ } catch (error) {
3440
+ handleError(error)
3441
+ }
3442
+ }
3443
+
3444
+ function queueButton(label, action) {
3445
+ const button = document.createElement('button')
3446
+ button.type = 'button'
3447
+ button.className = 'queue-action'
3448
+ button.textContent = label
3449
+ button.addEventListener('click', action)
3450
+ return button
3451
+ }
3452
+
3453
+ function renderQueue(session) {
3454
+ const queued = Array.isArray(session.queued) ? session.queued : []
3455
+ if (state.queueEditingId !== null && !queued.some((item) => item.id === state.queueEditingId)) {
3456
+ state.queueEditingId = null
3457
+ state.queueDraft = ''
3458
+ }
3459
+ const signature = `${queued.map((item) => `${item.id}:${item.text.length}:${item.target}:${item.steerable}:${item.editable}`).join('|')}|${state.queueEditingId}`
3460
+ if (signature === state.queueSignature) {
3461
+ el.queueBar.hidden = queued.length === 0
3462
+ return
3463
+ }
3464
+ state.queueSignature = signature
3465
+ el.queueBar.replaceChildren()
3466
+ el.queueBar.hidden = queued.length === 0
3467
+ for (const item of queued) {
3468
+ const row = document.createElement('div')
3469
+ row.className = `queue-item${state.queueEditingId === item.id ? ' editing' : ''}`
3470
+ if (state.queueEditingId === item.id) {
3471
+ const input = document.createElement('textarea')
3472
+ input.rows = 2
3473
+ input.value = state.queueDraft
3474
+ input.addEventListener('input', () => {
3475
+ state.queueDraft = input.value
3476
+ })
3477
+ const actions = document.createElement('div')
3478
+ actions.className = 'queue-actions'
3479
+ actions.append(
3480
+ queueButton(t('保存'), () => void queueAction(item, 'edit', state.queueDraft.trim())),
3481
+ queueButton(t('取消'), () => {
3482
+ state.queueEditingId = null
3483
+ state.queueDraft = ''
3484
+ state.queueSignature = ''
3485
+ renderQueue(state.session)
3486
+ }),
3487
+ )
3488
+ row.append(input, actions)
3489
+ } else {
3490
+ const text = document.createElement('div')
3491
+ text.className = 'queue-text'
3492
+ text.textContent = item.text
3493
+ const actions = document.createElement('div')
3494
+ actions.className = 'queue-actions'
3495
+ if (item.steerable) actions.append(queueButton(t('插话'), () => void queueAction(item, 'steer')))
3496
+ if (item.editable !== false) {
3497
+ actions.append(queueButton(t('编辑'), () => {
3498
+ state.queueEditingId = item.id
3499
+ state.queueDraft = item.text
3500
+ state.queueSignature = ''
3501
+ renderQueue(state.session)
3502
+ const editor = el.queueBar.querySelector('.queue-item.editing textarea')
3503
+ editor?.focus()
3504
+ }))
3505
+ }
3506
+ actions.append(queueButton(t('删除'), () => void queueAction(item, 'remove')))
3507
+ row.append(text, actions)
3508
+ }
3509
+ el.queueBar.append(row)
3510
+ }
3511
+ }
3512
+
3513
+ async function queueAction(item, action, text) {
3514
+ if (state.sessionId === null) return
3515
+ if (action === 'edit' && (typeof text !== 'string' || text.length === 0)) return
3516
+ try {
3517
+ await post(API.queue, {
3518
+ sessionId: state.sessionId,
3519
+ itemId: item.id,
3520
+ action,
3521
+ ...(action === 'edit' ? { text } : {}),
3522
+ })
3523
+ state.queueEditingId = null
3524
+ state.queueDraft = ''
3525
+ state.queueSignature = ''
3526
+ await loadSession()
3527
+ } catch (error) {
3528
+ handleError(error)
3529
+ }
3530
+ }
3531
+
3532
+ async function goalCommand(line) {
3533
+ if (state.sessionId === null) return false
3534
+ const name = line.split(/\s+/)[0]
3535
+ let ok = false
3536
+ try {
3537
+ const outcome = await runCommandLine(line)
3538
+ if (outcome.unknown) showBanner(t('未知或不完整的指令:{name}', { name }))
3539
+ else if (!outcome.ok) showBanner(outcome.text || t('指令执行失败'))
3540
+ else ok = true
3541
+ } catch (error) {
3542
+ handleError(error)
3543
+ }
3544
+ if (ok) {
3545
+ state.goalEditing = false
3546
+ el.goalEditor.hidden = true
3547
+ }
3548
+ await loadSession()
3549
+ return ok
3550
+ }
3551
+
3552
+ async function exitPlanMode() {
3553
+ const plan = state.session?.plan
3554
+ if (state.sessionId === null || plan?.active !== true || plan?.pending === true) return
3555
+ try {
3556
+ const outcome = await runCommandLine('/plan off')
3557
+ if (!outcome.ok) {
3558
+ showBanner(outcome.text || t('无法关闭计划模式'))
3559
+ return
3560
+ }
3561
+ await loadSession()
3562
+ showBanner(t('已关闭计划模式'), false, 'ok')
3563
+ } catch (error) {
3564
+ handleError(error)
3565
+ }
3566
+ }
3567
+
3568
+ function startGoalEdit() {
3569
+ const goal = state.session?.goal
3570
+ if (!goal) return
3571
+ state.goalEditing = true
3572
+ el.goalInput.value = goal.objective
3573
+ el.goalEditor.hidden = false
3574
+ el.goalInput.focus()
3575
+ }
3576
+
3577
+ function cancelGoalEdit() {
3578
+ state.goalEditing = false
3579
+ el.goalEditor.hidden = true
3580
+ }
3581
+
3582
+ async function saveGoalEdit() {
3583
+ const objective = el.goalInput.value.trim()
3584
+ if (objective.length === 0) return
3585
+ const goal = state.session?.goal
3586
+ await goalCommand(goal ? `/goal edit ${objective}` : `/goal ${objective}`)
3587
+ }
3588
+
3589
+ function openSheet() {
3590
+ el.sheet.hidden = false
3591
+ document.body.classList.add('sheet-open')
3592
+ renderSessionList()
3593
+ if (archivedVisible()) void loadArchivedSessions()
3594
+ }
3595
+
3596
+ function closeSheet() {
3597
+ closeViewMenu()
3598
+ closeAppearancePanel()
3599
+ el.sheet.hidden = true
3600
+ document.body.classList.remove('sheet-open')
3601
+ }
3602
+
3603
+ function resizePrompt() {
3604
+ el.prompt.style.height = 'auto'
3605
+ el.prompt.style.height = `${Math.min(el.prompt.scrollHeight, 200)}px`
3606
+ }
3607
+
3608
+ function shortPath(path) {
3609
+ if (typeof path !== 'string') return ''
3610
+ const parts = path.split('/').filter(Boolean)
3611
+ if (parts.length <= 2) return path
3612
+ return `…/${parts.slice(-2).join('/')}`
3613
+ }
3614
+
3615
+ function basenameOf(path) {
3616
+ if (typeof path !== 'string') return ''
3617
+ const trimmed = path.replace(/\/+$/, '')
3618
+ const index = trimmed.lastIndexOf('/')
3619
+ return index < 0 ? trimmed : trimmed.slice(index + 1)
3620
+ }
3621
+
3622
+ function relativeTime(value) {
3623
+ if (typeof value !== 'number' || !Number.isFinite(value)) return ''
3624
+ const seconds = Math.round((Date.now() - value) / 1000)
3625
+ if (seconds < 45) return t('刚刚')
3626
+ if (seconds < 3600) return t('{count} 分钟前', { count: Math.round(seconds / 60) })
3627
+ if (seconds < 86400) return t('{count} 小时前', { count: Math.round(seconds / 3600) })
3628
+ if (seconds < 86400 * 7) return t('{count} 天前', { count: Math.round(seconds / 86400) })
3629
+ return new Intl.DateTimeFormat(currentLanguage() === 'zh' ? 'zh-CN' : 'en-US', {
3630
+ month: 'numeric',
3631
+ day: 'numeric',
3632
+ }).format(new Date(value))
3633
+ }
3634
+
3635
+ function wireEvents() {
3636
+ el.sessionsButton.addEventListener('click', openSheet)
3637
+ el.refreshButton.addEventListener('click', () => {
3638
+ void loadBootstrap(true)
3639
+ if (state.sessionId !== null) void loadSession()
3640
+ })
3641
+ el.send.addEventListener('click', () => void sendPrompt())
3642
+ el.stop.addEventListener('click', () => void stopTurn())
3643
+ el.newSessionButton.addEventListener('click', () => void newSession())
3644
+ el.themeToggle.addEventListener('click', () => {
3645
+ toggleColorMode()
3646
+ })
3647
+ el.appearanceButton.addEventListener('click', (event) => {
3648
+ event.stopPropagation()
3649
+ toggleAppearancePanel()
3650
+ })
3651
+ el.appearanceClose.addEventListener('click', closeAppearancePanel)
3652
+ wireRadioGroup(el.themeFamilyOptions, '.appearance-option')
3653
+ wireRadioGroup(el.themeModeOptions, '.appearance-mode')
3654
+ document.addEventListener(THEME_CHANGE_EVENT, () => {
3655
+ renderThemeToggle()
3656
+ if (state.appearanceOpen) renderAppearanceOptions()
3657
+ })
3658
+ el.langToggle.addEventListener('click', toggleLanguage)
3659
+ el.fullPageButton.addEventListener('click', openFullPage)
3660
+ el.notifyToggle.addEventListener('click', () => void toggleNotifications())
3661
+ el.contextMeter.addEventListener('click', () => void showInsights())
3662
+ el.planChip.addEventListener('click', () => void exitPlanMode())
3663
+ el.viewMenuButton.addEventListener('click', (event) => {
3664
+ event.stopPropagation()
3665
+ toggleViewMenu()
3666
+ })
3667
+ for (const button of el.viewMenu.querySelectorAll('[data-view-group]')) {
3668
+ button.addEventListener('click', () => setListView(button.dataset.viewGroup))
3669
+ }
3670
+ for (const button of el.viewMenu.querySelectorAll('[data-view-sort]')) {
3671
+ button.addEventListener('click', () => setListSort(button.dataset.viewSort))
3672
+ }
3673
+ for (const button of el.viewMenu.querySelectorAll('[data-view-archived]')) {
3674
+ button.addEventListener('click', () => setArchivedFilter(button.dataset.viewArchived))
3675
+ }
3676
+ document.addEventListener('pointerdown', (event) => {
3677
+ if (state.viewMenuOpen
3678
+ && !el.viewMenu.contains(event.target)
3679
+ && !el.viewMenuButton.contains(event.target)) closeViewMenu()
3680
+ if (state.appearanceOpen
3681
+ && !el.appearancePanel.contains(event.target)
3682
+ && !el.appearanceButton.contains(event.target)) closeAppearancePanel()
3683
+ })
3684
+ document.addEventListener('keydown', (event) => {
3685
+ if (event.key !== 'Escape') return
3686
+ if (state.viewMenuOpen) {
3687
+ closeViewMenu()
3688
+ el.viewMenuButton.focus()
3689
+ }
3690
+ if (state.appearanceOpen) closeAppearancePanel()
3691
+ })
3692
+ el.modelSelect.addEventListener('change', () => {
3693
+ const [provider, model] = el.modelSelect.value.split('\u0000')
3694
+ if (provider && model) syncEffort({ provider, model })
3695
+ void selectModel()
3696
+ })
3697
+ el.effortSelect.addEventListener('change', () => void selectModel())
3698
+ el.presetSelect.addEventListener('change', () => savePresetId(el.presetSelect.value))
3699
+ el.sessionSearch.addEventListener('input', onSearchInput)
3700
+ el.loadMoreButton.addEventListener('click', loadMoreSessions)
3701
+ el.modelRefresh.addEventListener('click', () => void refreshModels())
3702
+ el.loadEarlier.addEventListener('click', () => void loadEarlier())
3703
+ el.goalToggle.addEventListener('click', () => {
3704
+ const expanded = el.goalBar.classList.toggle('expanded')
3705
+ el.goalToggle.setAttribute('aria-expanded', expanded ? 'true' : 'false')
3706
+ })
3707
+ el.goalPause.addEventListener('click', () => {
3708
+ const phase = state.session?.goal?.phase
3709
+ void goalCommand(phase === 'paused' || phase === 'blocked' ? '/goal resume' : '/goal pause')
3710
+ })
3711
+ el.goalEdit.addEventListener('click', startGoalEdit)
3712
+ el.goalDelete.addEventListener('click', () => {
3713
+ void (async () => {
3714
+ const confirmed = await showDialog({
3715
+ title: t('删除目标'),
3716
+ message: t('删除后当前目标会从会话中移除。'),
3717
+ confirmText: t('删除'),
3718
+ cancelText: t('取消'),
3719
+ danger: true,
3720
+ })
3721
+ if (confirmed === true) void goalCommand('/goal clear')
3722
+ })()
3723
+ })
3724
+ el.goalSave.addEventListener('click', () => void saveGoalEdit())
3725
+ el.goalCancel.addEventListener('click', cancelGoalEdit)
3726
+ el.sheet.addEventListener('click', (event) => {
3727
+ if (event.target.closest('[data-close-sheet]')) closeSheet()
3728
+ })
3729
+ el.dialog.addEventListener('click', (event) => {
3730
+ if (event.target.closest('[data-dialog-cancel]')) closeDialog(null)
3731
+ })
3732
+ el.dialogInput.addEventListener('keydown', (event) => {
3733
+ if (event.key !== 'Enter') return
3734
+ event.preventDefault()
3735
+ el.dialogActions.querySelector('.dialog-action.primary, .dialog-action.danger')?.click()
3736
+ })
3737
+ document.addEventListener('keydown', (event) => {
3738
+ if (event.key === 'Escape' && !el.dialog.hidden) {
3739
+ event.preventDefault()
3740
+ closeDialog(null)
3741
+ }
3742
+ })
3743
+ el.messages.addEventListener('click', (event) => {
3744
+ const button = event.target.closest('.code-copy')
3745
+ if (!(button instanceof HTMLElement)) return
3746
+ const code = button.closest('.code-block')?.querySelector('code')
3747
+ if (!(code instanceof HTMLElement)) return
3748
+ void (async () => {
3749
+ const copied = await copyText(code.textContent ?? '')
3750
+ button.textContent = copied ? t('已复制') : t('复制失败')
3751
+ setTimeout(() => {
3752
+ button.textContent = t('复制')
3753
+ }, 1400)
3754
+ })()
3755
+ })
3756
+ el.prompt.addEventListener('input', () => {
3757
+ resizePrompt()
3758
+ saveCurrentDraft()
3759
+ void updateCommandMenu()
3760
+ })
3761
+ el.imageButton.addEventListener('click', () => el.imageInput.click())
3762
+ el.imageInput.addEventListener('change', () => {
3763
+ const files = el.imageInput.files === null ? [] : [...el.imageInput.files]
3764
+ el.imageInput.value = ''
3765
+ if (files.length > 0) void addImages(files)
3766
+ })
3767
+ el.prompt.addEventListener('blur', () => {
3768
+ setTimeout(hideCommandMenu, 120)
3769
+ })
3770
+ el.prompt.addEventListener('keydown', (event) => {
3771
+ if (event.key === 'Escape') hideCommandMenu()
3772
+ })
3773
+ const scroller = el.messages.parentElement
3774
+ if (scroller !== null) {
3775
+ scroller.addEventListener('scroll', updateScrollButton, { passive: true })
3776
+ }
3777
+ el.scrollBottom.addEventListener('click', () => {
3778
+ if (scroller === null) return
3779
+ scroller.scrollTo({ top: scroller.scrollHeight, behavior: 'smooth' })
3780
+ })
3781
+ document.addEventListener('visibilitychange', () => {
3782
+ if (document.visibilityState === 'visible') {
3783
+ setUnread(false)
3784
+ if (state.sessionId !== null) void loadSession()
3785
+ } else {
3786
+ if (completionNotificationsEnabled() && state.session?.running === true) schedulePoll(HIDDEN_POLL_MS)
3787
+ else if (state.timer !== null) {
3788
+ clearTimeout(state.timer)
3789
+ state.timer = null
3790
+ }
3791
+ saveCurrentDraft()
3792
+ writeDrafts()
3793
+ }
3794
+ })
3795
+ window.addEventListener('beforeunload', () => {
3796
+ saveCurrentDraft()
3797
+ writeDrafts()
3798
+ })
3799
+ window.addEventListener('online', () => {
3800
+ void loadBootstrap()
3801
+ if (state.sessionId !== null) void loadSession()
3802
+ })
3803
+ window.addEventListener('resize', updateScrollButton)
3804
+ window.visualViewport?.addEventListener('resize', updateScrollButton)
3805
+ window.addEventListener('beforeinstallprompt', (event) => {
3806
+ event.preventDefault()
3807
+ state.installPrompt = event
3808
+ })
3809
+ }
3810
+
3811
+ async function boot() {
3812
+ initLanguage()
3813
+ applyStaticTranslations()
3814
+ initTheme()
3815
+ renderLanguageToggle()
3816
+ renderThemeToggle()
3817
+ renderAppearanceOptions()
3818
+ wireEvents()
3819
+ state.linkedSessionId = linkedSessionId()
3820
+ if (state.linkedSessionId !== null) {
3821
+ try { history.replaceState(null, '', location.pathname) } catch { /* non-fatal */ }
3822
+ }
3823
+ state.notifyEnabled = completionNotifyPreference()
3824
+ renderNotifyToggle()
3825
+ state.listView = readListView()
3826
+ state.listSort = readListSort()
3827
+ state.archivedFilter = readArchivedFilter()
3828
+ state.collapsedGroups = readCollapsedGroups()
3829
+ state.drafts = readDrafts()
3830
+ restoreDraft()
3831
+ const cached = cachedBootstrap()
3832
+ if (cached !== null) {
3833
+ state.bootstrap = cached
3834
+ state.activeTotal = Number.isInteger(cached.activeTotal) ? cached.activeTotal : cached.sessions.length
3835
+ state.activeHasMore = cached.activeHasMore === true
3836
+ state.pagedSearch = Number.isInteger(cached.activeTotal)
3837
+ renderSessionList()
3838
+ renderModelOptions()
3839
+ const candidate = state.linkedSessionId ?? savedSessionId()
3840
+ const linkedKnown = state.linkedSessionId === null
3841
+ ? undefined
3842
+ : cached.sessions.find((session) => session.id === state.linkedSessionId)
3843
+ const first = linkedKnown
3844
+ ?? cached.sessions.find((session) => session.id === candidate)
3845
+ ?? (state.linkedSessionId === null ? cached.sessions[0] : undefined)
3846
+ if (first) {
3847
+ state.sessionId = first.id
3848
+ if (first.id === state.linkedSessionId) state.linkedSessionId = null
3849
+ renderHeader(first)
3850
+ renderEmpty(t('加载中…'))
3851
+ restoreDraft()
3852
+ }
3853
+ }
3854
+ await loadBootstrap()
3855
+ if (archivedVisible()) void loadArchivedSessions(true)
3856
+ if (state.session === null && state.sessionId !== null && state.loadingSession === 0) void loadSession()
3857
+ if (window.matchMedia('(min-width: 720px) and (max-width: 899px)').matches) openSheet()
3858
+ resizePrompt()
3859
+ if ('serviceWorker' in navigator) {
3860
+ navigator.serviceWorker.addEventListener('message', (event) => {
3861
+ const data = event.data
3862
+ if (data?.type === 'dsh-lite:open-session' && typeof data.sessionId === 'string' && data.sessionId.length > 0) {
3863
+ openSession(data.sessionId)
3864
+ }
3865
+ })
3866
+ navigator.serviceWorker.register('/lite/sw.js', { scope: '/lite/' }).catch(() => {})
3867
+ }
3868
+ }
3869
+
3870
+ void boot()