dsh-lite 0.0.0-stage → 0.6.2

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