codexmate 0.0.27 → 0.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +421 -421
  2. package/README.zh.md +354 -354
  3. package/cli/agents-files.js +224 -224
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +375 -375
  6. package/cli/builtin-proxy.js +1620 -1299
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +384 -384
  9. package/cli/config-health.js +338 -338
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/openai-bridge.js +1489 -1091
  13. package/cli/openclaw-config.js +629 -629
  14. package/cli/session-convert-args.js +65 -65
  15. package/cli/session-convert-io.js +82 -82
  16. package/cli/session-convert.js +43 -43
  17. package/cli/session-usage.concurrent.js +28 -28
  18. package/cli/session-usage.js +118 -118
  19. package/cli/session-usage.models.js +176 -176
  20. package/cli/skills.js +1141 -1141
  21. package/cli/zip-commands.js +510 -510
  22. package/cli.js +15264 -15251
  23. package/lib/automation.js +404 -404
  24. package/lib/cli-file-utils.js +151 -151
  25. package/lib/cli-models-utils.js +440 -379
  26. package/lib/cli-network-utils.js +190 -190
  27. package/lib/cli-path-utils.js +85 -85
  28. package/lib/cli-session-utils.js +121 -121
  29. package/lib/cli-sessions.js +417 -417
  30. package/lib/cli-utils.js +155 -155
  31. package/lib/download-artifacts.js +92 -92
  32. package/lib/mcp-stdio.js +453 -453
  33. package/lib/task-orchestrator.js +869 -869
  34. package/lib/text-diff.js +303 -303
  35. package/lib/workflow-engine.js +340 -340
  36. package/package.json +3 -1
  37. package/plugins/README.md +20 -20
  38. package/plugins/README.zh-CN.md +20 -20
  39. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  40. package/plugins/prompt-templates/computed.mjs +253 -253
  41. package/plugins/prompt-templates/index.mjs +8 -8
  42. package/plugins/prompt-templates/manifest.mjs +15 -15
  43. package/plugins/prompt-templates/methods.mjs +553 -619
  44. package/plugins/prompt-templates/overview.mjs +91 -90
  45. package/plugins/prompt-templates/ownership.mjs +19 -19
  46. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  47. package/plugins/prompt-templates/storage.mjs +64 -64
  48. package/plugins/registry.mjs +16 -16
  49. package/web-ui/app.js +625 -634
  50. package/web-ui/index.html +35 -35
  51. package/web-ui/logic.agents-diff.mjs +386 -386
  52. package/web-ui/logic.claude.mjs +168 -168
  53. package/web-ui/logic.codex.mjs +56 -0
  54. package/web-ui/logic.mjs +5 -5
  55. package/web-ui/logic.runtime.mjs +128 -128
  56. package/web-ui/logic.session-convert.mjs +70 -70
  57. package/web-ui/logic.sessions.mjs +765 -765
  58. package/web-ui/modules/api.mjs +90 -90
  59. package/web-ui/modules/app.computed.dashboard.mjs +225 -171
  60. package/web-ui/modules/app.computed.index.mjs +17 -17
  61. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  62. package/web-ui/modules/app.computed.session.mjs +994 -994
  63. package/web-ui/modules/app.constants.mjs +15 -15
  64. package/web-ui/modules/app.methods.agents.mjs +632 -632
  65. package/web-ui/modules/app.methods.claude-config.mjs +190 -184
  66. package/web-ui/modules/app.methods.codex-config.mjs +892 -860
  67. package/web-ui/modules/app.methods.index.mjs +92 -92
  68. package/web-ui/modules/app.methods.install.mjs +205 -205
  69. package/web-ui/modules/app.methods.navigation.mjs +743 -743
  70. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  71. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  72. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  73. package/web-ui/modules/app.methods.providers.mjs +412 -404
  74. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  75. package/web-ui/modules/app.methods.session-actions.mjs +593 -596
  76. package/web-ui/modules/app.methods.session-browser.mjs +984 -989
  77. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  78. package/web-ui/modules/app.methods.session-trash.mjs +439 -439
  79. package/web-ui/modules/app.methods.startup-claude.mjs +533 -526
  80. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  81. package/web-ui/modules/config-mode.computed.mjs +124 -124
  82. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  83. package/web-ui/modules/i18n.dict.mjs +2109 -2131
  84. package/web-ui/modules/i18n.mjs +56 -56
  85. package/web-ui/modules/plugins.computed.mjs +3 -3
  86. package/web-ui/modules/plugins.methods.mjs +3 -3
  87. package/web-ui/modules/plugins.storage.mjs +11 -11
  88. package/web-ui/modules/provider-url-display.mjs +17 -0
  89. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  90. package/web-ui/modules/skills.computed.mjs +107 -107
  91. package/web-ui/modules/skills.methods.mjs +481 -481
  92. package/web-ui/partials/index/layout-footer.html +13 -13
  93. package/web-ui/partials/index/layout-header.html +475 -475
  94. package/web-ui/partials/index/modal-config-template-agents.html +174 -174
  95. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  96. package/web-ui/partials/index/modal-health-check.html +45 -45
  97. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  98. package/web-ui/partials/index/modal-skills.html +200 -200
  99. package/web-ui/partials/index/modals-basic.html +165 -165
  100. package/web-ui/partials/index/panel-config-claude.html +188 -187
  101. package/web-ui/partials/index/panel-config-codex.html +312 -283
  102. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  103. package/web-ui/partials/index/panel-dashboard.html +186 -186
  104. package/web-ui/partials/index/panel-docs.html +147 -147
  105. package/web-ui/partials/index/panel-market.html +177 -177
  106. package/web-ui/partials/index/panel-orchestration.html +391 -391
  107. package/web-ui/partials/index/panel-plugins.html +253 -279
  108. package/web-ui/partials/index/panel-sessions.html +316 -326
  109. package/web-ui/partials/index/panel-settings.html +253 -274
  110. package/web-ui/partials/index/panel-usage.html +371 -371
  111. package/web-ui/res/json5.min.js +1 -1
  112. package/web-ui/res/vue.global.prod.js +13 -13
  113. package/web-ui/session-helpers.mjs +576 -576
  114. package/web-ui/source-bundle.cjs +233 -233
  115. package/web-ui/styles/base-theme.css +281 -268
  116. package/web-ui/styles/controls-forms.css +422 -423
  117. package/web-ui/styles/dashboard.css +274 -274
  118. package/web-ui/styles/docs-panel.css +247 -247
  119. package/web-ui/styles/feedback.css +108 -108
  120. package/web-ui/styles/health-check-dialog.css +144 -144
  121. package/web-ui/styles/layout-shell.css +606 -603
  122. package/web-ui/styles/modals-core.css +466 -464
  123. package/web-ui/styles/navigation-panels.css +391 -390
  124. package/web-ui/styles/openclaw-structured.css +266 -266
  125. package/web-ui/styles/plugins-panel.css +523 -523
  126. package/web-ui/styles/responsive.css +454 -454
  127. package/web-ui/styles/sessions-list.css +419 -415
  128. package/web-ui/styles/sessions-preview.css +411 -411
  129. package/web-ui/styles/sessions-toolbar-trash.css +330 -330
  130. package/web-ui/styles/sessions-usage.css +1040 -1040
  131. package/web-ui/styles/settings-panel.css +185 -185
  132. package/web-ui/styles/skills-list.css +303 -303
  133. package/web-ui/styles/skills-market.css +406 -406
  134. package/web-ui/styles/task-orchestration.css +822 -822
  135. package/web-ui/styles/titles-cards.css +472 -408
  136. package/web-ui/styles.css +21 -21
  137. package/web-ui.html +17 -17
@@ -1,989 +1,984 @@
1
- import {
2
- buildSessionFilterCacheState,
3
- isSessionQueryEnabled,
4
- normalizeSessionMessageRole,
5
- normalizeSessionPathFilter
6
- } from '../logic.mjs';
7
- import {
8
- applySessionsFilterUrlState,
9
- buildSessionsFilterShareUrl,
10
- normalizeSessionRoleFilter,
11
- normalizeSessionTimePreset,
12
- readSessionsFilterUrlState,
13
- syncSessionsFilterUrl
14
- } from './sessions-filters-url.mjs';
15
-
16
- function isSessionLoadNativeDialogEnabled(vm) {
17
- if (vm && typeof vm.isSessionLoadNativeDialogEnabled === 'function' && vm.isSessionLoadNativeDialogEnabled !== isSessionLoadNativeDialogEnabled) {
18
- try {
19
- return !!vm.isSessionLoadNativeDialogEnabled();
20
- } catch (_) {
21
- // fall through to shared detection
22
- }
23
- }
24
-
25
- try {
26
- if (globalThis && globalThis.__CODEXMATE_SESSION_LOAD_NATIVE_DIALOG__ === true) {
27
- return true;
28
- }
29
- } catch (_) {
30
- // ignore global flag lookup failures
31
- }
32
-
33
- try {
34
- if (typeof localStorage !== 'undefined' && typeof localStorage.getItem === 'function') {
35
- const stored = String(localStorage.getItem('codexmateSessionLoadNativeDialog') || '').trim().toLowerCase();
36
- if (stored === '1' || stored === 'true' || stored === 'yes' || stored === 'on') {
37
- return true;
38
- }
39
- }
40
- } catch (_) {
41
- // ignore storage lookup failures
42
- }
43
-
44
- try {
45
- const search = typeof location !== 'undefined' && location && typeof location.search === 'string'
46
- ? location.search
47
- : (typeof window !== 'undefined' && window.location && typeof window.location.search === 'string'
48
- ? window.location.search
49
- : '');
50
- if (!search) {
51
- return false;
52
- }
53
- const params = new URLSearchParams(search);
54
- const value = String(params.get('sessionLoadNativeDialog') || '').trim().toLowerCase();
55
- return value === '1' || value === 'true' || value === 'yes' || value === 'on';
56
- } catch (_) {
57
- return false;
58
- }
59
- }
60
-
61
- function emitSessionLoadNativeDialog(vm, step, details = '') {
62
- if (!isSessionLoadNativeDialogEnabled(vm)) {
63
- return;
64
- }
65
- const alertFn = typeof globalThis.alert === 'function'
66
- ? globalThis.alert.bind(globalThis)
67
- : (typeof window !== 'undefined' && typeof window.alert === 'function'
68
- ? window.alert.bind(window)
69
- : null);
70
- if (!alertFn) {
71
- return;
72
- }
73
- const message = details
74
- ? `[codexmate][session-load] ${step}\n${details}`
75
- : `[codexmate][session-load] ${step}`;
76
- alertFn(message);
77
- }
78
-
79
- export function createSessionBrowserMethods(options = {}) {
80
- const {
81
- api,
82
- loadSessionsHelper,
83
- loadActiveSessionDetailHelper
84
- } = options;
85
-
86
- return {
87
- normalizeSessionPathValue(value) {
88
- return normalizeSessionPathFilter(value);
89
- },
90
-
91
- mergeSessionPathOptions(baseList = [], incomingList = []) {
92
- const merged = [];
93
- const seen = new Set();
94
- const append = (items) => {
95
- if (!Array.isArray(items)) return;
96
- for (const item of items) {
97
- const value = this.normalizeSessionPathValue(item);
98
- if (!value) continue;
99
- const key = value.toLowerCase();
100
- if (seen.has(key)) continue;
101
- seen.add(key);
102
- merged.push(value);
103
- }
104
- };
105
-
106
- append(baseList);
107
- append(incomingList);
108
- return merged;
109
- },
110
-
111
- extractPathOptionsFromSessions(sessions) {
112
- const paths = [];
113
- if (!Array.isArray(sessions)) {
114
- return paths;
115
- }
116
-
117
- const seen = new Set();
118
- for (const session of sessions) {
119
- const value = this.normalizeSessionPathValue(session && session.cwd ? session.cwd : '');
120
- if (!value) continue;
121
- const key = value.toLowerCase();
122
- if (seen.has(key)) continue;
123
- seen.add(key);
124
- paths.push(value);
125
- }
126
- return paths;
127
- },
128
-
129
- syncSessionPathOptionsForSource(source, nextOptions, mergeWithExisting = false) {
130
- const targetSource = source === 'claude'
131
- ? 'claude'
132
- : (source === 'gemini' ? 'gemini' : (source === 'all' ? 'all' : 'codex'));
133
- const current = Array.isArray(this.sessionPathOptionsMap[targetSource])
134
- ? this.sessionPathOptionsMap[targetSource]
135
- : [];
136
- const merged = mergeWithExisting
137
- ? this.mergeSessionPathOptions(current, nextOptions)
138
- : this.mergeSessionPathOptions([], nextOptions);
139
- this.sessionPathOptionsMap = {
140
- ...this.sessionPathOptionsMap,
141
- [targetSource]: merged
142
- };
143
- this.refreshSessionPathOptions(targetSource);
144
- },
145
-
146
- refreshSessionPathOptions(source) {
147
- const targetSource = source === 'claude'
148
- ? 'claude'
149
- : (source === 'gemini' ? 'gemini' : (source === 'all' ? 'all' : 'codex'));
150
- const base = Array.isArray(this.sessionPathOptionsMap[targetSource])
151
- ? [...this.sessionPathOptionsMap[targetSource]]
152
- : [];
153
- const selected = this.normalizeSessionPathValue(this.sessionPathFilter);
154
- if (selected && !base.some(item => item.toLowerCase() === selected.toLowerCase())) {
155
- base.unshift(selected);
156
- }
157
- if (targetSource === this.sessionFilterSource) {
158
- this.sessionPathOptions = base;
159
- }
160
- },
161
-
162
- isSessionLoadNativeDialogEnabled() {
163
- return isSessionLoadNativeDialogEnabled(this);
164
- },
165
-
166
- emitSessionLoadNativeDialog(step, details = '') {
167
- emitSessionLoadNativeDialog(this, step, details);
168
- },
169
-
170
- async loadSessionPathOptions(options = {}) {
171
- const source = options.source === 'claude'
172
- ? 'claude'
173
- : (options.source === 'gemini' ? 'gemini' : (options.source === 'all' ? 'all' : 'codex'));
174
- const forceRefresh = !!options.forceRefresh;
175
- const loaded = !!this.sessionPathOptionsLoadedMap[source];
176
- if (!forceRefresh && loaded) {
177
- emitSessionLoadNativeDialog(this, 'loadSessionPathOptions:cache-hit', `source=${source}`);
178
- if (source === this.sessionFilterSource) {
179
- this.sessionPathOptionsLoading = false;
180
- }
181
- return;
182
- }
183
-
184
- const nextSeqMap = {
185
- ...(this.sessionPathRequestSeqMap || {})
186
- };
187
- const requestSeq = (Number(nextSeqMap[source]) || 0) + 1;
188
- nextSeqMap[source] = requestSeq;
189
- this.sessionPathRequestSeqMap = nextSeqMap;
190
- emitSessionLoadNativeDialog(
191
- this,
192
- 'loadSessionPathOptions:start',
193
- `source=${source}\nforceRefresh=${forceRefresh}\nrequestSeq=${requestSeq}`
194
- );
195
- if (source === this.sessionFilterSource) {
196
- this.sessionPathOptionsLoading = true;
197
- }
198
- try {
199
- const res = await api('list-session-paths', {
200
- source,
201
- limit: 500,
202
- forceRefresh
203
- });
204
- if (requestSeq !== Number(((this.sessionPathRequestSeqMap || {})[source]) || 0)) {
205
- emitSessionLoadNativeDialog(
206
- this,
207
- 'loadSessionPathOptions:stale-response',
208
- `source=${source}\nrequestSeq=${requestSeq}`
209
- );
210
- return;
211
- }
212
- if (res && !res.error && Array.isArray(res.paths)) {
213
- this.syncSessionPathOptionsForSource(source, res.paths, true);
214
- this.sessionPathOptionsLoadedMap = {
215
- ...this.sessionPathOptionsLoadedMap,
216
- [source]: true
217
- };
218
- emitSessionLoadNativeDialog(
219
- this,
220
- 'loadSessionPathOptions:success',
221
- `source=${source}\npaths=${res.paths.length}`
222
- );
223
- } else if (res && res.error) {
224
- emitSessionLoadNativeDialog(
225
- this,
226
- 'loadSessionPathOptions:error',
227
- `source=${source}\nerror=${res.error}`
228
- );
229
- }
230
- } catch (error) {
231
- emitSessionLoadNativeDialog(
232
- this,
233
- 'loadSessionPathOptions:exception',
234
- `source=${source}\nerror=${error && error.message ? error.message : String(error)}`
235
- );
236
- // 路径补全失败不影响会话主流程
237
- } finally {
238
- if (
239
- source === this.sessionFilterSource
240
- && requestSeq === Number(((this.sessionPathRequestSeqMap || {})[source]) || 0)
241
- ) {
242
- this.sessionPathOptionsLoading = false;
243
- }
244
- emitSessionLoadNativeDialog(
245
- this,
246
- 'loadSessionPathOptions:complete',
247
- `source=${source}\nrequestSeq=${requestSeq}`
248
- );
249
- }
250
- },
251
-
252
- onSessionResumeYoloChange() {
253
- const value = this.sessionResumeWithYolo ? '1' : '0';
254
- localStorage.setItem('codexmateSessionResumeYolo', value);
255
- },
256
-
257
- normalizeSessionSortMode(value) {
258
- const normalized = typeof value === 'string' ? value.trim().toLowerCase() : '';
259
- return normalized === 'hot' ? 'hot' : 'time';
260
- },
261
-
262
- restoreSessionFilterCache() {
263
- const urlState = readSessionsFilterUrlState();
264
- const normalizeSortMode = typeof this.normalizeSessionSortMode === 'function'
265
- ? this.normalizeSessionSortMode.bind(this)
266
- : ((value) => {
267
- const normalized = typeof value === 'string' ? value.trim().toLowerCase() : '';
268
- return normalized === 'hot' ? 'hot' : 'time';
269
- });
270
- if (urlState) {
271
- applySessionsFilterUrlState(this, urlState);
272
- try {
273
- const sortCache = localStorage.getItem('codexmateSessionSortMode');
274
- this.sessionSortMode = normalizeSortMode(sortCache);
275
- } catch (_) {}
276
- if (this.mainTab === 'sessions' && typeof this.loadSessions === 'function') {
277
- void this.loadSessions();
278
- }
279
- return;
280
- }
281
- const sourceCache = localStorage.getItem('codexmateSessionFilterSource');
282
- const pathCache = localStorage.getItem('codexmateSessionPathFilter');
283
- const cached = buildSessionFilterCacheState(sourceCache, pathCache);
284
- this.sessionFilterSource = cached.source;
285
- this.sessionPathFilter = cached.pathFilter;
286
- const queryCache = localStorage.getItem('codexmateSessionQuery');
287
- const roleCache = localStorage.getItem('codexmateSessionRoleFilter');
288
- const timeCache = localStorage.getItem('codexmateSessionTimePreset');
289
- const sortCache = localStorage.getItem('codexmateSessionSortMode');
290
- this.sessionQuery = typeof queryCache === 'string' ? queryCache : '';
291
- this.sessionRoleFilter = normalizeSessionRoleFilter(roleCache);
292
- this.sessionTimePreset = normalizeSessionTimePreset(timeCache);
293
- this.sessionSortMode = normalizeSortMode(sortCache);
294
- this.refreshSessionPathOptions(this.sessionFilterSource);
295
- if (this.mainTab === 'sessions' && typeof this.loadSessions === 'function') {
296
- const shouldReload = cached.source !== 'all'
297
- || !!cached.pathFilter
298
- || !!(this.sessionQuery && isSessionQueryEnabled(cached.source))
299
- || (this.sessionRoleFilter && this.sessionRoleFilter !== 'all')
300
- || (this.sessionTimePreset && this.sessionTimePreset !== 'all');
301
- if (shouldReload) {
302
- void this.loadSessions();
303
- }
304
- }
305
- },
306
-
307
- persistSessionFilterCache() {
308
- const cached = buildSessionFilterCacheState(this.sessionFilterSource, this.sessionPathFilter);
309
- localStorage.setItem('codexmateSessionFilterSource', cached.source);
310
- if (cached.pathFilter) {
311
- localStorage.setItem('codexmateSessionPathFilter', cached.pathFilter);
312
- } else {
313
- localStorage.removeItem('codexmateSessionPathFilter');
314
- }
315
- if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
316
- localStorage.setItem('codexmateSessionQuery', this.sessionQuery);
317
- } else {
318
- localStorage.removeItem('codexmateSessionQuery');
319
- }
320
- localStorage.setItem('codexmateSessionRoleFilter', normalizeSessionRoleFilter(this.sessionRoleFilter));
321
- localStorage.setItem('codexmateSessionTimePreset', normalizeSessionTimePreset(this.sessionTimePreset));
322
- },
323
-
324
- onSessionSortChange() {
325
- const normalized = this.normalizeSessionSortMode(this.sessionSortMode);
326
- this.sessionSortMode = normalized;
327
- try {
328
- localStorage.setItem('codexmateSessionSortMode', normalized);
329
- } catch (_) {}
330
- },
331
-
332
- getSessionHotLabel(session) {
333
- if (!session || typeof session !== 'object') return '';
334
- const updatedAtMs = Date.parse(session.updatedAt || '');
335
- if (!Number.isFinite(updatedAtMs)) return '';
336
- const ageMs = Date.now() - updatedAtMs;
337
- if (!Number.isFinite(ageMs) || ageMs < 0) return '';
338
- const messageCount = Number.isFinite(Number(session.messageCount))
339
- ? Math.max(0, Math.floor(Number(session.messageCount)))
340
- : 0;
341
- if (ageMs <= (24 * 60 * 60 * 1000) && messageCount >= 20) {
342
- return typeof this.t === 'function' ? this.t('sessions.sort.hotBadge') : '热';
343
- }
344
- return '';
345
- },
346
-
347
- normalizeSessionPinnedMap(raw) {
348
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
349
- return {};
350
- }
351
- const next = {};
352
- for (const [key, value] of Object.entries(raw)) {
353
- if (!key) continue;
354
- const numeric = Number(value);
355
- if (!Number.isFinite(numeric) || numeric <= 0) continue;
356
- next[key] = Math.floor(numeric);
357
- }
358
- return next;
359
- },
360
-
361
- restoreSessionPinnedMap() {
362
- const cached = localStorage.getItem('codexmateSessionPinnedMap');
363
- if (!cached) {
364
- this.sessionPinnedMap = {};
365
- return;
366
- }
367
- try {
368
- const parsed = JSON.parse(cached);
369
- this.sessionPinnedMap = this.normalizeSessionPinnedMap(parsed);
370
- } catch (_) {
371
- this.sessionPinnedMap = {};
372
- localStorage.removeItem('codexmateSessionPinnedMap');
373
- }
374
- },
375
-
376
- persistSessionPinnedMap() {
377
- const payload = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
378
- ? this.sessionPinnedMap
379
- : {};
380
- localStorage.setItem('codexmateSessionPinnedMap', JSON.stringify(payload));
381
- },
382
-
383
- shouldPruneSessionPinnedMap(sessions = this.sessionsList) {
384
- if (!Array.isArray(sessions) || sessions.length === 0) {
385
- return false;
386
- }
387
- if (this.sessionFilterSource !== 'all') {
388
- return false;
389
- }
390
- if (this.sessionPathFilter) {
391
- return false;
392
- }
393
- if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
394
- return false;
395
- }
396
- if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') {
397
- return false;
398
- }
399
- if (this.sessionTimePreset && this.sessionTimePreset !== 'all') {
400
- return false;
401
- }
402
- return true;
403
- },
404
-
405
- pruneSessionPinnedMap(sessions = this.sessionsList) {
406
- const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
407
- ? this.sessionPinnedMap
408
- : {};
409
- const list = Array.isArray(sessions) ? sessions : [];
410
- if (Object.keys(current).length === 0 || !this.shouldPruneSessionPinnedMap(list)) {
411
- return;
412
- }
413
- const validKeys = new Set(list.map((session) => this.getSessionExportKey(session)).filter(Boolean));
414
- const next = {};
415
- let changed = false;
416
- for (const [key, value] of Object.entries(current)) {
417
- if (!validKeys.has(key)) {
418
- changed = true;
419
- continue;
420
- }
421
- next[key] = value;
422
- }
423
- if (!changed) {
424
- return;
425
- }
426
- this.sessionPinnedMap = next;
427
- this.persistSessionPinnedMap();
428
- },
429
-
430
- getSessionPinTimestamp(session) {
431
- if (!session) return 0;
432
- const key = this.getSessionExportKey(session);
433
- if (!key) return 0;
434
- const raw = this.sessionPinnedMap && this.sessionPinnedMap[key];
435
- const numeric = Number(raw);
436
- return Number.isFinite(numeric) && numeric > 0 ? Math.floor(numeric) : 0;
437
- },
438
-
439
- isSessionPinned(session) {
440
- return this.getSessionPinTimestamp(session) > 0;
441
- },
442
-
443
- toggleSessionPin(session) {
444
- if (!session) return;
445
- const key = this.getSessionExportKey(session);
446
- if (!key) return;
447
- const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
448
- ? this.sessionPinnedMap
449
- : {};
450
- const next = { ...current };
451
- if (next[key]) {
452
- delete next[key];
453
- } else {
454
- next[key] = Date.now();
455
- }
456
- this.sessionPinnedMap = next;
457
- this.persistSessionPinnedMap();
458
- },
459
-
460
- removeSessionPin(session) {
461
- if (!session) return;
462
- const key = this.getSessionExportKey(session);
463
- if (!key) return;
464
- const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
465
- ? this.sessionPinnedMap
466
- : {};
467
- if (!current[key]) return;
468
- const next = { ...current };
469
- delete next[key];
470
- this.sessionPinnedMap = next;
471
- this.persistSessionPinnedMap();
472
- },
473
-
474
- async onSessionSourceChange(event) {
475
- const rawValue = event && event.target && typeof event.target.value === 'string'
476
- ? event.target.value
477
- : this.sessionFilterSource;
478
- const cached = buildSessionFilterCacheState(rawValue, this.sessionPathFilter);
479
- this.sessionFilterSource = cached.source;
480
- this.refreshSessionPathOptions(this.sessionFilterSource);
481
- this.persistSessionFilterCache();
482
- syncSessionsFilterUrl(this);
483
- await this.loadSessions();
484
- },
485
-
486
- async onSessionPathFilterChange() {
487
- this.persistSessionFilterCache();
488
- syncSessionsFilterUrl(this);
489
- await this.loadSessions();
490
- },
491
-
492
- async onSessionFilterChange() {
493
- this.persistSessionFilterCache();
494
- syncSessionsFilterUrl(this);
495
- await this.loadSessions();
496
- },
497
-
498
- hasActiveSessionFilters() {
499
- if (this.sessionFilterSource && this.sessionFilterSource !== 'all') return true;
500
- if (this.sessionPathFilter) return true;
501
- if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) return true;
502
- if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') return true;
503
- if (this.sessionTimePreset && this.sessionTimePreset !== 'all') return true;
504
- return false;
505
- },
506
-
507
- getSessionFilterChips() {
508
- const chips = [];
509
- if (this.sessionFilterSource && this.sessionFilterSource !== 'all') {
510
- const label = this.sessionFilterSource === 'codex'
511
- ? this.t('sessions.source.codex')
512
- : (this.sessionFilterSource === 'claude'
513
- ? this.t('sessions.source.claudeCode')
514
- : (this.sessionFilterSource === 'gemini'
515
- ? this.t('sessions.source.gemini')
516
- : (this.sessionFilterSource === 'codebuddy' ? this.t('sessions.source.codebuddy') : this.sessionFilterSource)));
517
- chips.push({ key: 'source', title: this.t('sessions.filters.source'), value: label });
518
- }
519
- if (this.sessionPathFilter) {
520
- chips.push({ key: 'path', title: this.t('sessions.filters.path'), value: this.sessionPathFilter });
521
- }
522
- if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
523
- chips.push({ key: 'query', title: this.t('sessions.filters.keyword'), value: this.sessionQuery });
524
- }
525
- if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') {
526
- const label = this.sessionRoleFilter === 'user'
527
- ? this.t('sessions.role.user')
528
- : (this.sessionRoleFilter === 'assistant'
529
- ? this.t('sessions.role.assistant')
530
- : (this.sessionRoleFilter === 'system' ? this.t('sessions.role.system') : this.sessionRoleFilter));
531
- chips.push({ key: 'role', title: this.t('sessions.filters.role'), value: label });
532
- }
533
- if (this.sessionTimePreset && this.sessionTimePreset !== 'all') {
534
- const label = this.sessionTimePreset === '7d'
535
- ? this.t('sessions.time.7d')
536
- : (this.sessionTimePreset === '30d'
537
- ? this.t('sessions.time.30d')
538
- : (this.sessionTimePreset === '90d' ? this.t('sessions.time.90d') : this.sessionTimePreset));
539
- chips.push({ key: 'time', title: this.t('sessions.filters.time'), value: label });
540
- }
541
- return chips;
542
- },
543
-
544
- async clearSessionFilterChip(key) {
545
- const normalized = typeof key === 'string' ? key.trim().toLowerCase() : '';
546
- if (normalized === 'source') this.sessionFilterSource = 'all';
547
- if (normalized === 'path') this.sessionPathFilter = '';
548
- if (normalized === 'query') this.sessionQuery = '';
549
- if (normalized === 'role') this.sessionRoleFilter = 'all';
550
- if (normalized === 'time') this.sessionTimePreset = 'all';
551
- this.persistSessionFilterCache();
552
- syncSessionsFilterUrl(this);
553
- await this.loadSessions();
554
- },
555
-
556
- async clearSessionFilters() {
557
- this.sessionFilterSource = 'all';
558
- this.sessionPathFilter = '';
559
- this.sessionQuery = '';
560
- this.sessionRoleFilter = 'all';
561
- this.sessionTimePreset = 'all';
562
- this.persistSessionFilterCache();
563
- syncSessionsFilterUrl(this);
564
- await this.onSessionSourceChange();
565
- },
566
-
567
- async copySessionsFilterShareUrl() {
568
- const url = buildSessionsFilterShareUrl(this);
569
- if (!url) {
570
- this.showMessage(typeof this.t === 'function' ? this.t('sessions.filters.urlBuildFail') : 'Failed to build link', 'error');
571
- return;
572
- }
573
- try {
574
- if (navigator.clipboard && window.isSecureContext) {
575
- await navigator.clipboard.writeText(url);
576
- this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.ok') : 'Copied', 'success');
577
- return;
578
- }
579
- } catch (_) {}
580
- const ok = typeof this.fallbackCopyText === 'function' ? this.fallbackCopyText(url) : false;
581
- if (ok) {
582
- this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.ok') : 'Copied', 'success');
583
- return;
584
- }
585
- this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.fail') : 'Copy failed', 'error');
586
- },
587
-
588
- normalizeSessionMessage(message) {
589
- const fallback = {
590
- role: 'assistant',
591
- normalizedRole: 'assistant',
592
- roleLabel: 'Assistant',
593
- text: typeof message === 'string' ? message : '',
594
- timestamp: ''
595
- };
596
- const safeMessage = message && typeof message === 'object' ? message : fallback;
597
- const normalizedRole = normalizeSessionMessageRole(
598
- safeMessage.normalizedRole || safeMessage.role
599
- );
600
- const roleLabel = normalizedRole === 'user'
601
- ? 'User'
602
- : (normalizedRole === 'system' ? 'System' : 'Assistant');
603
- return {
604
- ...safeMessage,
605
- role: normalizedRole,
606
- normalizedRole,
607
- roleLabel
608
- };
609
- },
610
-
611
- getRecordKey(message) {
612
- if (!message || !Number.isInteger(message.recordLineIndex) || message.recordLineIndex < 0) {
613
- return '';
614
- }
615
- return String(message.recordLineIndex);
616
- },
617
-
618
- getRecordRenderKey(message, idx) {
619
- const recordKey = this.getRecordKey(message);
620
- if (recordKey) {
621
- return `record-${recordKey}`;
622
- }
623
- return `record-fallback-${idx}-${message && message.timestamp ? message.timestamp : ''}`;
624
- },
625
-
626
- syncActiveSessionMessageCount(messageCount) {
627
- if (!Number.isFinite(messageCount) || messageCount < 0) return;
628
- if (this.activeSession) {
629
- this.activeSession.messageCount = messageCount;
630
- }
631
- const activeKey = this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
632
- if (!activeKey) return;
633
- const matched = this.sessionsList.find(item => this.getSessionExportKey(item) === activeKey);
634
- if (matched) {
635
- matched.messageCount = messageCount;
636
- }
637
- },
638
-
639
- cancelScheduledSessionListMessageCountHydrate() {
640
- const handle = this.__sessionListMessageCountHydrateHandle || null;
641
- if (!handle) return;
642
- if (typeof this.cancelIdleTask === 'function') {
643
- this.cancelIdleTask(handle);
644
- }
645
- this.__sessionListMessageCountHydrateHandle = null;
646
- },
647
-
648
- resetSessionListMessageCountHydrate() {
649
- this.cancelScheduledSessionListMessageCountHydrate();
650
- this.__sessionListMessageCountHydrateInFlight = false;
651
- this.__sessionListMessageCountHydrateLastScheduleAt = 0;
652
- this.__sessionListMessageCountHydrateLastAttemptAtMap = {};
653
- this.sessionListMessageCountHydrateRequestSeq = (Number(this.sessionListMessageCountHydrateRequestSeq) || 0) + 1;
654
- },
655
-
656
- scheduleSessionListMessageCountHydrate() {
657
- if (this.mainTab !== 'sessions' || !this.sessionListRenderEnabled) {
658
- return;
659
- }
660
- const now = Date.now();
661
- const lastAt = Number(this.__sessionListMessageCountHydrateLastScheduleAt || 0);
662
- if ((now - lastAt) < 120) {
663
- return;
664
- }
665
- this.__sessionListMessageCountHydrateLastScheduleAt = now;
666
- this.cancelScheduledSessionListMessageCountHydrate();
667
- const run = () => {
668
- this.__sessionListMessageCountHydrateHandle = null;
669
- void this.hydrateVisibleSessionListMessageCounts();
670
- };
671
- if (typeof this.scheduleIdleTask === 'function') {
672
- this.__sessionListMessageCountHydrateHandle = this.scheduleIdleTask(run, 160);
673
- return;
674
- }
675
- if (typeof this.scheduleAfterFrame === 'function') {
676
- this.scheduleAfterFrame(run);
677
- return;
678
- }
679
- run();
680
- },
681
-
682
- async hydrateVisibleSessionListMessageCounts() {
683
- if (this.__sessionListMessageCountHydrateInFlight) {
684
- return;
685
- }
686
- if (this.mainTab !== 'sessions' || !this.sessionListRenderEnabled) {
687
- return;
688
- }
689
-
690
- const visible = Array.isArray(this.visibleSessionsList) ? this.visibleSessionsList : [];
691
- if (!visible.length) return;
692
-
693
- const now = Date.now();
694
- const lastAttemptAtMap = (this.__sessionListMessageCountHydrateLastAttemptAtMap && typeof this.__sessionListMessageCountHydrateLastAttemptAtMap === 'object')
695
- ? this.__sessionListMessageCountHydrateLastAttemptAtMap
696
- : {};
697
- const targets = [];
698
- for (const session of visible) {
699
- if (!session || typeof session !== 'object') continue;
700
- const messageCountRaw = Number(session.messageCount);
701
- const shouldHydrate = !Number.isFinite(messageCountRaw) || messageCountRaw === 0;
702
- if (!shouldHydrate) continue;
703
- const key = this.getSessionExportKey(session);
704
- if (!key) continue;
705
- const lastAttempt = Number(lastAttemptAtMap[key] || 0);
706
- if ((now - lastAttempt) < 5000) {
707
- continue;
708
- }
709
- lastAttemptAtMap[key] = now;
710
- targets.push({
711
- source: session.source,
712
- sessionId: session.sessionId,
713
- filePath: session.filePath
714
- });
715
- if (targets.length >= 32) {
716
- break;
717
- }
718
- }
719
- this.__sessionListMessageCountHydrateLastAttemptAtMap = lastAttemptAtMap;
720
- if (!targets.length) return;
721
-
722
- const requestSeq = (Number(this.sessionListMessageCountHydrateRequestSeq) || 0) + 1;
723
- this.sessionListMessageCountHydrateRequestSeq = requestSeq;
724
- this.__sessionListMessageCountHydrateInFlight = true;
725
- try {
726
- const res = await api('session-message-counts', {
727
- items: targets,
728
- limit: targets.length
729
- });
730
- if (requestSeq !== Number(this.sessionListMessageCountHydrateRequestSeq || 0)) {
731
- return;
732
- }
733
- if (!res || res.error || !Array.isArray(res.items)) {
734
- return;
735
- }
736
- const byKey = new Map();
737
- for (const item of res.items) {
738
- if (!item || typeof item !== 'object') continue;
739
- const key = typeof item.key === 'string' ? item.key : '';
740
- if (!key) continue;
741
- const messageCount = Number(item.messageCount);
742
- if (!Number.isFinite(messageCount) || messageCount < 0) continue;
743
- byKey.set(key, Math.floor(messageCount));
744
- }
745
- if (!byKey.size) {
746
- return;
747
- }
748
- const sessions = Array.isArray(this.sessionsList) ? this.sessionsList : [];
749
- const sessionMap = new Map(sessions.map((session) => [this.getSessionExportKey(session), session]));
750
- for (const [key, count] of byKey.entries()) {
751
- const matched = sessionMap.get(key);
752
- if (matched) {
753
- matched.messageCount = count;
754
- }
755
- if (this.activeSession && this.getSessionExportKey(this.activeSession) === key) {
756
- this.activeSession.messageCount = count;
757
- }
758
- }
759
- } catch (_) {
760
- return;
761
- } finally {
762
- if (requestSeq === Number(this.sessionListMessageCountHydrateRequestSeq || 0)) {
763
- this.__sessionListMessageCountHydrateInFlight = false;
764
- }
765
- }
766
- },
767
-
768
- invalidateSessionsUsageData(options = {}) {
769
- this.sessionsUsageLoadedOnce = false;
770
- this.sessionsUsageLoadedLimit = 0;
771
- this.sessionsUsageError = '';
772
- if (options.preserveList !== true) {
773
- this.sessionsUsageList = [];
774
- }
775
- },
776
-
777
- setSessionsUsageTimeRange(nextRange) {
778
- const normalized = typeof nextRange === 'string' ? nextRange.trim().toLowerCase() : '';
779
- const range = normalized === 'all' ? 'all' : (normalized === '30d' ? '30d' : '7d');
780
- this.sessionsUsageTimeRange = range;
781
- try { localStorage.setItem('sessionsUsageTimeRange', range); } catch (_) {}
782
- if (range === 'all') {
783
- this.sessionsUsageCompareEnabled = false;
784
- }
785
- void this.loadSessionsUsage({ range });
786
- },
787
-
788
- toggleSessionsUsageCompare() {
789
- if (this.sessionsUsageTimeRange === 'all') {
790
- this.sessionsUsageCompareEnabled = false;
791
- return;
792
- }
793
- this.sessionsUsageCompareEnabled = !this.sessionsUsageCompareEnabled;
794
- const range = typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '7d';
795
- void this.loadSessionsUsage({
796
- range,
797
- limit: this.sessionsUsageCompareEnabled ? 2000 : undefined
798
- });
799
- },
800
-
801
- selectSessionsUsageDay(dayKey) {
802
- const normalized = typeof dayKey === 'string' ? dayKey.trim() : '';
803
- this.sessionsUsageSelectedDayKey = normalized;
804
- },
805
-
806
- clearSessionsUsageDay() {
807
- this.sessionsUsageSelectedDayKey = '';
808
- },
809
-
810
- async loadSessionsUsage(options = {}) {
811
- if (this.sessionsUsageLoading) return;
812
- const normalizedRange = typeof options.range === 'string'
813
- ? options.range.trim().toLowerCase()
814
- : (typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '');
815
- const range = normalizedRange === 'all' ? 'all' : (normalizedRange === '30d' ? '30d' : '7d');
816
- const defaultLimit = range === 'all' ? 2000 : (range === '30d' ? 1200 : 600);
817
- const rawLimit = Number(options.limit);
818
- const compareBoost = this.sessionsUsageCompareEnabled && range !== 'all'
819
- ? 2000
820
- : defaultLimit;
821
- const limit = Number.isFinite(rawLimit)
822
- ? Math.max(1, Math.min(rawLimit, 2000))
823
- : compareBoost;
824
- const loadedLimit = Number(this.sessionsUsageLoadedLimit || 0);
825
- if (this.sessionsUsageLoadedOnce && !options.forceRefresh && loadedLimit >= limit) {
826
- return;
827
- }
828
- this.sessionsUsageLoading = true;
829
- this.sessionsUsageError = '';
830
- let loadSucceeded = false;
831
- try {
832
- const res = await api('list-sessions-usage', {
833
- source: 'all',
834
- limit,
835
- forceRefresh: !!options.forceRefresh
836
- });
837
- if (res.error) {
838
- this.sessionsUsageError = res.error;
839
- this.showMessage(res.error, 'error');
840
- return;
841
- }
842
- this.sessionsUsageList = Array.isArray(res.sessions) ? res.sessions : [];
843
- loadSucceeded = true;
844
- } catch (e) {
845
- this.sessionsUsageError = '加载 usage 统计失败';
846
- this.showMessage('加载 usage 统计失败', 'error');
847
- } finally {
848
- this.sessionsUsageLoading = false;
849
- if (loadSucceeded) {
850
- this.sessionsUsageLoadedOnce = true;
851
- this.sessionsUsageLoadedLimit = limit;
852
- if (!this.sessionsUsageSelectedDayKey && Array.isArray(this.sessionUsageDailyTableRows) && this.sessionUsageDailyTableRows.length > 0) {
853
- this.sessionsUsageSelectedDayKey = this.sessionUsageDailyTableRows[0].key;
854
- }
855
- }
856
- }
857
- },
858
-
859
- async loadSessions(options = {}) {
860
- this.resetSessionListMessageCountHydrate();
861
- const result = await loadSessionsHelper.call(this, api, options || {});
862
- this.pruneSessionPinnedMap(this.sessionsList);
863
- return result;
864
- },
865
-
866
- async selectSession(session) {
867
- if (!session) {
868
- emitSessionLoadNativeDialog(this, 'selectSession:skip-empty');
869
- return;
870
- }
871
- emitSessionLoadNativeDialog(
872
- this,
873
- 'selectSession:start',
874
- `sessionId=${session.sessionId || ''}\nsource=${session.source || ''}`
875
- );
876
- const isSameSession = this.activeSession
877
- && this.getSessionExportKey(this.activeSession) === this.getSessionExportKey(session);
878
- if (isSameSession) {
879
- emitSessionLoadNativeDialog(this, 'selectSession:same-session', `sessionId=${session.sessionId || ''}`);
880
- if (this.sessionDetailLoading) {
881
- emitSessionLoadNativeDialog(this, 'selectSession:skip-detail-loading', `sessionId=${session.sessionId || ''}`);
882
- return;
883
- }
884
- const currentMessages = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages : [];
885
- if (currentMessages.length > 0) {
886
- emitSessionLoadNativeDialog(
887
- this,
888
- 'selectSession:skip-existing-messages',
889
- `sessionId=${session.sessionId || ''}\nmessages=${currentMessages.length}`
890
- );
891
- return;
892
- }
893
- if (typeof this.scheduleAfterFrame === 'function') {
894
- const selectedSession = this.activeSession;
895
- emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
896
- this.scheduleAfterFrame(() => {
897
- if (this.activeSession !== selectedSession) return;
898
- void this.loadActiveSessionDetail();
899
- });
900
- return;
901
- }
902
- emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
903
- await this.loadActiveSessionDetail();
904
- return;
905
- }
906
- this.activeSession = session;
907
- emitSessionLoadNativeDialog(this, 'selectSession:activate', `sessionId=${session.sessionId || ''}`);
908
- if (typeof this.expandVisibleSessionList === 'function') {
909
- this.expandVisibleSessionList(0, { ensureActive: true });
910
- }
911
- this.activeSessionMessages = [];
912
- this.resetSessionDetailPagination();
913
- this.resetSessionPreviewMessageRender();
914
- this.activeSessionDetailError = '';
915
- this.activeSessionDetailClipped = false;
916
- this.cancelSessionTimelineSync();
917
- this.sessionTimelineActiveKey = '';
918
- this.clearSessionTimelineRefs();
919
- if (typeof this.scheduleAfterFrame === 'function') {
920
- const selectedSession = this.activeSession;
921
- emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
922
- this.scheduleAfterFrame(() => {
923
- if (this.activeSession !== selectedSession) return;
924
- void this.loadActiveSessionDetail();
925
- });
926
- return;
927
- }
928
- emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
929
- await this.loadActiveSessionDetail();
930
- },
931
-
932
- async loadSessionStandalonePlain() {
933
- if (!this.activeSession) {
934
- this.sessionStandaloneRequestSeq += 1;
935
- this.sessionStandaloneLoading = false;
936
- this.sessionStandaloneText = '';
937
- this.sessionStandaloneTitle = '会话';
938
- this.sessionStandaloneSourceLabel = '';
939
- this.sessionStandaloneError = '';
940
- return;
941
- }
942
-
943
- const requestSeq = ++this.sessionStandaloneRequestSeq;
944
- const sessionSnapshot = this.activeSession;
945
- this.sessionStandaloneLoading = true;
946
- this.sessionStandaloneError = '';
947
- try {
948
- const res = await api('session-plain', {
949
- source: sessionSnapshot.source,
950
- sessionId: sessionSnapshot.sessionId,
951
- filePath: sessionSnapshot.filePath,
952
- maxMessages: sessionSnapshot.maxMessages || 50
953
- });
954
-
955
- if (requestSeq !== this.sessionStandaloneRequestSeq) {
956
- return;
957
- }
958
-
959
- if (res.error) {
960
- this.sessionStandaloneText = '';
961
- this.sessionStandaloneError = res.error;
962
- return;
963
- }
964
-
965
- this.sessionStandaloneSourceLabel = res.sourceLabel || sessionSnapshot.sourceLabel || '';
966
- this.sessionStandaloneTitle = res.sessionId || sessionSnapshot.title || '会话';
967
- this.sessionStandaloneText = typeof res.text === 'string' ? res.text : '';
968
- } catch (e) {
969
- if (requestSeq !== this.sessionStandaloneRequestSeq) {
970
- return;
971
- }
972
- this.sessionStandaloneText = '';
973
- this.sessionStandaloneError = '加载会话内容失败: ' + e.message;
974
- } finally {
975
- if (requestSeq === this.sessionStandaloneRequestSeq) {
976
- this.sessionStandaloneLoading = false;
977
- }
978
- }
979
- },
980
-
981
- async loadActiveSessionDetail(options = {}) {
982
- const result = await loadActiveSessionDetailHelper.call(this, api, options);
983
- if (this.mainTab === 'sessions' && typeof this.scheduleSessionListMessageCountHydrate === 'function') {
984
- this.scheduleSessionListMessageCountHydrate();
985
- }
986
- return result;
987
- }
988
- };
989
- }
1
+ import {
2
+ buildSessionFilterCacheState,
3
+ isSessionQueryEnabled,
4
+ normalizeSessionMessageRole,
5
+ normalizeSessionPathFilter
6
+ } from '../logic.mjs';
7
+ import {
8
+ applySessionsFilterUrlState,
9
+ buildSessionsFilterShareUrl,
10
+ normalizeSessionRoleFilter,
11
+ normalizeSessionTimePreset,
12
+ readSessionsFilterUrlState,
13
+ syncSessionsFilterUrl
14
+ } from './sessions-filters-url.mjs';
15
+
16
+ function isSessionLoadNativeDialogEnabled(vm) {
17
+ if (vm && typeof vm.isSessionLoadNativeDialogEnabled === 'function' && vm.isSessionLoadNativeDialogEnabled !== isSessionLoadNativeDialogEnabled) {
18
+ try {
19
+ return !!vm.isSessionLoadNativeDialogEnabled();
20
+ } catch (_) {
21
+ // fall through to shared detection
22
+ }
23
+ }
24
+
25
+ try {
26
+ if (globalThis && globalThis.__CODEXMATE_SESSION_LOAD_NATIVE_DIALOG__ === true) {
27
+ return true;
28
+ }
29
+ } catch (_) {
30
+ // ignore global flag lookup failures
31
+ }
32
+
33
+ try {
34
+ if (typeof localStorage !== 'undefined' && typeof localStorage.getItem === 'function') {
35
+ const stored = String(localStorage.getItem('codexmateSessionLoadNativeDialog') || '').trim().toLowerCase();
36
+ if (stored === '1' || stored === 'true' || stored === 'yes' || stored === 'on') {
37
+ return true;
38
+ }
39
+ }
40
+ } catch (_) {
41
+ // ignore storage lookup failures
42
+ }
43
+
44
+ try {
45
+ const search = typeof location !== 'undefined' && location && typeof location.search === 'string'
46
+ ? location.search
47
+ : (typeof window !== 'undefined' && window.location && typeof window.location.search === 'string'
48
+ ? window.location.search
49
+ : '');
50
+ if (!search) {
51
+ return false;
52
+ }
53
+ const params = new URLSearchParams(search);
54
+ const value = String(params.get('sessionLoadNativeDialog') || '').trim().toLowerCase();
55
+ return value === '1' || value === 'true' || value === 'yes' || value === 'on';
56
+ } catch (_) {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ function emitSessionLoadNativeDialog(vm, step, details = '') {
62
+ if (!isSessionLoadNativeDialogEnabled(vm)) {
63
+ return;
64
+ }
65
+ const alertFn = typeof globalThis.alert === 'function'
66
+ ? globalThis.alert.bind(globalThis)
67
+ : (typeof window !== 'undefined' && typeof window.alert === 'function'
68
+ ? window.alert.bind(window)
69
+ : null);
70
+ if (!alertFn) {
71
+ return;
72
+ }
73
+ const message = details
74
+ ? `[codexmate][session-load] ${step}\n${details}`
75
+ : `[codexmate][session-load] ${step}`;
76
+ alertFn(message);
77
+ }
78
+
79
+ export function createSessionBrowserMethods(options = {}) {
80
+ const {
81
+ api,
82
+ loadSessionsHelper,
83
+ loadActiveSessionDetailHelper
84
+ } = options;
85
+
86
+ return {
87
+ normalizeSessionPathValue(value) {
88
+ return normalizeSessionPathFilter(value);
89
+ },
90
+
91
+ mergeSessionPathOptions(baseList = [], incomingList = []) {
92
+ const merged = [];
93
+ const seen = new Set();
94
+ const append = (items) => {
95
+ if (!Array.isArray(items)) return;
96
+ for (const item of items) {
97
+ const value = this.normalizeSessionPathValue(item);
98
+ if (!value) continue;
99
+ const key = value.toLowerCase();
100
+ if (seen.has(key)) continue;
101
+ seen.add(key);
102
+ merged.push(value);
103
+ }
104
+ };
105
+
106
+ append(baseList);
107
+ append(incomingList);
108
+ return merged;
109
+ },
110
+
111
+ extractPathOptionsFromSessions(sessions) {
112
+ const paths = [];
113
+ if (!Array.isArray(sessions)) {
114
+ return paths;
115
+ }
116
+
117
+ const seen = new Set();
118
+ for (const session of sessions) {
119
+ const value = this.normalizeSessionPathValue(session && session.cwd ? session.cwd : '');
120
+ if (!value) continue;
121
+ const key = value.toLowerCase();
122
+ if (seen.has(key)) continue;
123
+ seen.add(key);
124
+ paths.push(value);
125
+ }
126
+ return paths;
127
+ },
128
+
129
+ syncSessionPathOptionsForSource(source, nextOptions, mergeWithExisting = false) {
130
+ const targetSource = source === 'claude'
131
+ ? 'claude'
132
+ : (source === 'gemini' ? 'gemini' : (source === 'all' ? 'all' : 'codex'));
133
+ const current = Array.isArray(this.sessionPathOptionsMap[targetSource])
134
+ ? this.sessionPathOptionsMap[targetSource]
135
+ : [];
136
+ const merged = mergeWithExisting
137
+ ? this.mergeSessionPathOptions(current, nextOptions)
138
+ : this.mergeSessionPathOptions([], nextOptions);
139
+ this.sessionPathOptionsMap = {
140
+ ...this.sessionPathOptionsMap,
141
+ [targetSource]: merged
142
+ };
143
+ this.refreshSessionPathOptions(targetSource);
144
+ },
145
+
146
+ refreshSessionPathOptions(source) {
147
+ const targetSource = source === 'claude'
148
+ ? 'claude'
149
+ : (source === 'gemini' ? 'gemini' : (source === 'all' ? 'all' : 'codex'));
150
+ const base = Array.isArray(this.sessionPathOptionsMap[targetSource])
151
+ ? [...this.sessionPathOptionsMap[targetSource]]
152
+ : [];
153
+ const selected = this.normalizeSessionPathValue(this.sessionPathFilter);
154
+ if (selected && !base.some(item => item.toLowerCase() === selected.toLowerCase())) {
155
+ base.unshift(selected);
156
+ }
157
+ if (targetSource === this.sessionFilterSource) {
158
+ this.sessionPathOptions = base;
159
+ }
160
+ },
161
+
162
+ isSessionLoadNativeDialogEnabled() {
163
+ return isSessionLoadNativeDialogEnabled(this);
164
+ },
165
+
166
+ emitSessionLoadNativeDialog(step, details = '') {
167
+ emitSessionLoadNativeDialog(this, step, details);
168
+ },
169
+
170
+ async loadSessionPathOptions(options = {}) {
171
+ const source = options.source === 'claude'
172
+ ? 'claude'
173
+ : (options.source === 'gemini' ? 'gemini' : (options.source === 'all' ? 'all' : 'codex'));
174
+ const forceRefresh = !!options.forceRefresh;
175
+ const loaded = !!this.sessionPathOptionsLoadedMap[source];
176
+ if (!forceRefresh && loaded) {
177
+ emitSessionLoadNativeDialog(this, 'loadSessionPathOptions:cache-hit', `source=${source}`);
178
+ if (source === this.sessionFilterSource) {
179
+ this.sessionPathOptionsLoading = false;
180
+ }
181
+ return;
182
+ }
183
+
184
+ const nextSeqMap = {
185
+ ...(this.sessionPathRequestSeqMap || {})
186
+ };
187
+ const requestSeq = (Number(nextSeqMap[source]) || 0) + 1;
188
+ nextSeqMap[source] = requestSeq;
189
+ this.sessionPathRequestSeqMap = nextSeqMap;
190
+ emitSessionLoadNativeDialog(
191
+ this,
192
+ 'loadSessionPathOptions:start',
193
+ `source=${source}\nforceRefresh=${forceRefresh}\nrequestSeq=${requestSeq}`
194
+ );
195
+ if (source === this.sessionFilterSource) {
196
+ this.sessionPathOptionsLoading = true;
197
+ }
198
+ try {
199
+ const res = await api('list-session-paths', {
200
+ source,
201
+ limit: 500,
202
+ forceRefresh
203
+ });
204
+ if (requestSeq !== Number(((this.sessionPathRequestSeqMap || {})[source]) || 0)) {
205
+ emitSessionLoadNativeDialog(
206
+ this,
207
+ 'loadSessionPathOptions:stale-response',
208
+ `source=${source}\nrequestSeq=${requestSeq}`
209
+ );
210
+ return;
211
+ }
212
+ if (res && !res.error && Array.isArray(res.paths)) {
213
+ this.syncSessionPathOptionsForSource(source, res.paths, true);
214
+ this.sessionPathOptionsLoadedMap = {
215
+ ...this.sessionPathOptionsLoadedMap,
216
+ [source]: true
217
+ };
218
+ emitSessionLoadNativeDialog(
219
+ this,
220
+ 'loadSessionPathOptions:success',
221
+ `source=${source}\npaths=${res.paths.length}`
222
+ );
223
+ } else if (res && res.error) {
224
+ emitSessionLoadNativeDialog(
225
+ this,
226
+ 'loadSessionPathOptions:error',
227
+ `source=${source}\nerror=${res.error}`
228
+ );
229
+ }
230
+ } catch (error) {
231
+ emitSessionLoadNativeDialog(
232
+ this,
233
+ 'loadSessionPathOptions:exception',
234
+ `source=${source}\nerror=${error && error.message ? error.message : String(error)}`
235
+ );
236
+ // 路径补全失败不影响会话主流程
237
+ } finally {
238
+ if (
239
+ source === this.sessionFilterSource
240
+ && requestSeq === Number(((this.sessionPathRequestSeqMap || {})[source]) || 0)
241
+ ) {
242
+ this.sessionPathOptionsLoading = false;
243
+ }
244
+ emitSessionLoadNativeDialog(
245
+ this,
246
+ 'loadSessionPathOptions:complete',
247
+ `source=${source}\nrequestSeq=${requestSeq}`
248
+ );
249
+ }
250
+ },
251
+
252
+ normalizeSessionSortMode(value) {
253
+ const normalized = typeof value === 'string' ? value.trim().toLowerCase() : '';
254
+ return normalized === 'hot' ? 'hot' : 'time';
255
+ },
256
+
257
+ restoreSessionFilterCache() {
258
+ const urlState = readSessionsFilterUrlState();
259
+ const normalizeSortMode = typeof this.normalizeSessionSortMode === 'function'
260
+ ? this.normalizeSessionSortMode.bind(this)
261
+ : ((value) => {
262
+ const normalized = typeof value === 'string' ? value.trim().toLowerCase() : '';
263
+ return normalized === 'hot' ? 'hot' : 'time';
264
+ });
265
+ if (urlState) {
266
+ applySessionsFilterUrlState(this, urlState);
267
+ try {
268
+ const sortCache = localStorage.getItem('codexmateSessionSortMode');
269
+ this.sessionSortMode = normalizeSortMode(sortCache);
270
+ } catch (_) {}
271
+ if (this.mainTab === 'sessions' && typeof this.loadSessions === 'function') {
272
+ void this.loadSessions();
273
+ }
274
+ return;
275
+ }
276
+ const sourceCache = localStorage.getItem('codexmateSessionFilterSource');
277
+ const pathCache = localStorage.getItem('codexmateSessionPathFilter');
278
+ const cached = buildSessionFilterCacheState(sourceCache, pathCache);
279
+ this.sessionFilterSource = cached.source;
280
+ this.sessionPathFilter = cached.pathFilter;
281
+ const queryCache = localStorage.getItem('codexmateSessionQuery');
282
+ const roleCache = localStorage.getItem('codexmateSessionRoleFilter');
283
+ const timeCache = localStorage.getItem('codexmateSessionTimePreset');
284
+ const sortCache = localStorage.getItem('codexmateSessionSortMode');
285
+ this.sessionQuery = typeof queryCache === 'string' ? queryCache : '';
286
+ this.sessionRoleFilter = normalizeSessionRoleFilter(roleCache);
287
+ this.sessionTimePreset = normalizeSessionTimePreset(timeCache);
288
+ this.sessionSortMode = normalizeSortMode(sortCache);
289
+ this.refreshSessionPathOptions(this.sessionFilterSource);
290
+ if (this.mainTab === 'sessions' && typeof this.loadSessions === 'function') {
291
+ const shouldReload = cached.source !== 'all'
292
+ || !!cached.pathFilter
293
+ || !!(this.sessionQuery && isSessionQueryEnabled(cached.source))
294
+ || (this.sessionRoleFilter && this.sessionRoleFilter !== 'all')
295
+ || (this.sessionTimePreset && this.sessionTimePreset !== 'all');
296
+ if (shouldReload) {
297
+ void this.loadSessions();
298
+ }
299
+ }
300
+ },
301
+
302
+ persistSessionFilterCache() {
303
+ const cached = buildSessionFilterCacheState(this.sessionFilterSource, this.sessionPathFilter);
304
+ localStorage.setItem('codexmateSessionFilterSource', cached.source);
305
+ if (cached.pathFilter) {
306
+ localStorage.setItem('codexmateSessionPathFilter', cached.pathFilter);
307
+ } else {
308
+ localStorage.removeItem('codexmateSessionPathFilter');
309
+ }
310
+ if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
311
+ localStorage.setItem('codexmateSessionQuery', this.sessionQuery);
312
+ } else {
313
+ localStorage.removeItem('codexmateSessionQuery');
314
+ }
315
+ localStorage.setItem('codexmateSessionRoleFilter', normalizeSessionRoleFilter(this.sessionRoleFilter));
316
+ localStorage.setItem('codexmateSessionTimePreset', normalizeSessionTimePreset(this.sessionTimePreset));
317
+ },
318
+
319
+ onSessionSortChange() {
320
+ const normalized = this.normalizeSessionSortMode(this.sessionSortMode);
321
+ this.sessionSortMode = normalized;
322
+ try {
323
+ localStorage.setItem('codexmateSessionSortMode', normalized);
324
+ } catch (_) {}
325
+ },
326
+
327
+ getSessionHotLabel(session) {
328
+ if (!session || typeof session !== 'object') return '';
329
+ const updatedAtMs = Date.parse(session.updatedAt || '');
330
+ if (!Number.isFinite(updatedAtMs)) return '';
331
+ const ageMs = Date.now() - updatedAtMs;
332
+ if (!Number.isFinite(ageMs) || ageMs < 0) return '';
333
+ const messageCount = Number.isFinite(Number(session.messageCount))
334
+ ? Math.max(0, Math.floor(Number(session.messageCount)))
335
+ : 0;
336
+ if (ageMs <= (24 * 60 * 60 * 1000) && messageCount >= 20) {
337
+ return typeof this.t === 'function' ? this.t('sessions.sort.hotBadge') : '';
338
+ }
339
+ return '';
340
+ },
341
+
342
+ normalizeSessionPinnedMap(raw) {
343
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
344
+ return {};
345
+ }
346
+ const next = {};
347
+ for (const [key, value] of Object.entries(raw)) {
348
+ if (!key) continue;
349
+ const numeric = Number(value);
350
+ if (!Number.isFinite(numeric) || numeric <= 0) continue;
351
+ next[key] = Math.floor(numeric);
352
+ }
353
+ return next;
354
+ },
355
+
356
+ restoreSessionPinnedMap() {
357
+ const cached = localStorage.getItem('codexmateSessionPinnedMap');
358
+ if (!cached) {
359
+ this.sessionPinnedMap = {};
360
+ return;
361
+ }
362
+ try {
363
+ const parsed = JSON.parse(cached);
364
+ this.sessionPinnedMap = this.normalizeSessionPinnedMap(parsed);
365
+ } catch (_) {
366
+ this.sessionPinnedMap = {};
367
+ localStorage.removeItem('codexmateSessionPinnedMap');
368
+ }
369
+ },
370
+
371
+ persistSessionPinnedMap() {
372
+ const payload = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
373
+ ? this.sessionPinnedMap
374
+ : {};
375
+ localStorage.setItem('codexmateSessionPinnedMap', JSON.stringify(payload));
376
+ },
377
+
378
+ shouldPruneSessionPinnedMap(sessions = this.sessionsList) {
379
+ if (!Array.isArray(sessions) || sessions.length === 0) {
380
+ return false;
381
+ }
382
+ if (this.sessionFilterSource !== 'all') {
383
+ return false;
384
+ }
385
+ if (this.sessionPathFilter) {
386
+ return false;
387
+ }
388
+ if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
389
+ return false;
390
+ }
391
+ if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') {
392
+ return false;
393
+ }
394
+ if (this.sessionTimePreset && this.sessionTimePreset !== 'all') {
395
+ return false;
396
+ }
397
+ return true;
398
+ },
399
+
400
+ pruneSessionPinnedMap(sessions = this.sessionsList) {
401
+ const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
402
+ ? this.sessionPinnedMap
403
+ : {};
404
+ const list = Array.isArray(sessions) ? sessions : [];
405
+ if (Object.keys(current).length === 0 || !this.shouldPruneSessionPinnedMap(list)) {
406
+ return;
407
+ }
408
+ const validKeys = new Set(list.map((session) => this.getSessionExportKey(session)).filter(Boolean));
409
+ const next = {};
410
+ let changed = false;
411
+ for (const [key, value] of Object.entries(current)) {
412
+ if (!validKeys.has(key)) {
413
+ changed = true;
414
+ continue;
415
+ }
416
+ next[key] = value;
417
+ }
418
+ if (!changed) {
419
+ return;
420
+ }
421
+ this.sessionPinnedMap = next;
422
+ this.persistSessionPinnedMap();
423
+ },
424
+
425
+ getSessionPinTimestamp(session) {
426
+ if (!session) return 0;
427
+ const key = this.getSessionExportKey(session);
428
+ if (!key) return 0;
429
+ const raw = this.sessionPinnedMap && this.sessionPinnedMap[key];
430
+ const numeric = Number(raw);
431
+ return Number.isFinite(numeric) && numeric > 0 ? Math.floor(numeric) : 0;
432
+ },
433
+
434
+ isSessionPinned(session) {
435
+ return this.getSessionPinTimestamp(session) > 0;
436
+ },
437
+
438
+ toggleSessionPin(session) {
439
+ if (!session) return;
440
+ const key = this.getSessionExportKey(session);
441
+ if (!key) return;
442
+ const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
443
+ ? this.sessionPinnedMap
444
+ : {};
445
+ const next = { ...current };
446
+ if (next[key]) {
447
+ delete next[key];
448
+ } else {
449
+ next[key] = Date.now();
450
+ }
451
+ this.sessionPinnedMap = next;
452
+ this.persistSessionPinnedMap();
453
+ },
454
+
455
+ removeSessionPin(session) {
456
+ if (!session) return;
457
+ const key = this.getSessionExportKey(session);
458
+ if (!key) return;
459
+ const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
460
+ ? this.sessionPinnedMap
461
+ : {};
462
+ if (!current[key]) return;
463
+ const next = { ...current };
464
+ delete next[key];
465
+ this.sessionPinnedMap = next;
466
+ this.persistSessionPinnedMap();
467
+ },
468
+
469
+ async onSessionSourceChange(event) {
470
+ const rawValue = event && event.target && typeof event.target.value === 'string'
471
+ ? event.target.value
472
+ : this.sessionFilterSource;
473
+ const cached = buildSessionFilterCacheState(rawValue, this.sessionPathFilter);
474
+ this.sessionFilterSource = cached.source;
475
+ this.refreshSessionPathOptions(this.sessionFilterSource);
476
+ this.persistSessionFilterCache();
477
+ syncSessionsFilterUrl(this);
478
+ await this.loadSessions();
479
+ },
480
+
481
+ async onSessionPathFilterChange() {
482
+ this.persistSessionFilterCache();
483
+ syncSessionsFilterUrl(this);
484
+ await this.loadSessions();
485
+ },
486
+
487
+ async onSessionFilterChange() {
488
+ this.persistSessionFilterCache();
489
+ syncSessionsFilterUrl(this);
490
+ await this.loadSessions();
491
+ },
492
+
493
+ hasActiveSessionFilters() {
494
+ if (this.sessionFilterSource && this.sessionFilterSource !== 'all') return true;
495
+ if (this.sessionPathFilter) return true;
496
+ if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) return true;
497
+ if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') return true;
498
+ if (this.sessionTimePreset && this.sessionTimePreset !== 'all') return true;
499
+ return false;
500
+ },
501
+
502
+ getSessionFilterChips() {
503
+ const chips = [];
504
+ if (this.sessionFilterSource && this.sessionFilterSource !== 'all') {
505
+ const label = this.sessionFilterSource === 'codex'
506
+ ? this.t('sessions.source.codex')
507
+ : (this.sessionFilterSource === 'claude'
508
+ ? this.t('sessions.source.claudeCode')
509
+ : (this.sessionFilterSource === 'gemini'
510
+ ? this.t('sessions.source.gemini')
511
+ : (this.sessionFilterSource === 'codebuddy' ? this.t('sessions.source.codebuddy') : this.sessionFilterSource)));
512
+ chips.push({ key: 'source', title: this.t('sessions.filters.source'), value: label });
513
+ }
514
+ if (this.sessionPathFilter) {
515
+ chips.push({ key: 'path', title: this.t('sessions.filters.path'), value: this.sessionPathFilter });
516
+ }
517
+ if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
518
+ chips.push({ key: 'query', title: this.t('sessions.filters.keyword'), value: this.sessionQuery });
519
+ }
520
+ if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') {
521
+ const label = this.sessionRoleFilter === 'user'
522
+ ? this.t('sessions.role.user')
523
+ : (this.sessionRoleFilter === 'assistant'
524
+ ? this.t('sessions.role.assistant')
525
+ : (this.sessionRoleFilter === 'system' ? this.t('sessions.role.system') : this.sessionRoleFilter));
526
+ chips.push({ key: 'role', title: this.t('sessions.filters.role'), value: label });
527
+ }
528
+ if (this.sessionTimePreset && this.sessionTimePreset !== 'all') {
529
+ const label = this.sessionTimePreset === '7d'
530
+ ? this.t('sessions.time.7d')
531
+ : (this.sessionTimePreset === '30d'
532
+ ? this.t('sessions.time.30d')
533
+ : (this.sessionTimePreset === '90d' ? this.t('sessions.time.90d') : this.sessionTimePreset));
534
+ chips.push({ key: 'time', title: this.t('sessions.filters.time'), value: label });
535
+ }
536
+ return chips;
537
+ },
538
+
539
+ async clearSessionFilterChip(key) {
540
+ const normalized = typeof key === 'string' ? key.trim().toLowerCase() : '';
541
+ if (normalized === 'source') this.sessionFilterSource = 'all';
542
+ if (normalized === 'path') this.sessionPathFilter = '';
543
+ if (normalized === 'query') this.sessionQuery = '';
544
+ if (normalized === 'role') this.sessionRoleFilter = 'all';
545
+ if (normalized === 'time') this.sessionTimePreset = 'all';
546
+ this.persistSessionFilterCache();
547
+ syncSessionsFilterUrl(this);
548
+ await this.loadSessions();
549
+ },
550
+
551
+ async clearSessionFilters() {
552
+ this.sessionFilterSource = 'all';
553
+ this.sessionPathFilter = '';
554
+ this.sessionQuery = '';
555
+ this.sessionRoleFilter = 'all';
556
+ this.sessionTimePreset = 'all';
557
+ this.persistSessionFilterCache();
558
+ syncSessionsFilterUrl(this);
559
+ await this.onSessionSourceChange();
560
+ },
561
+
562
+ async copySessionsFilterShareUrl() {
563
+ const url = buildSessionsFilterShareUrl(this);
564
+ if (!url) {
565
+ this.showMessage(typeof this.t === 'function' ? this.t('sessions.filters.urlBuildFail') : 'Failed to build link', 'error');
566
+ return;
567
+ }
568
+ try {
569
+ if (navigator.clipboard && window.isSecureContext) {
570
+ await navigator.clipboard.writeText(url);
571
+ this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.ok') : 'Copied', 'success');
572
+ return;
573
+ }
574
+ } catch (_) {}
575
+ const ok = typeof this.fallbackCopyText === 'function' ? this.fallbackCopyText(url) : false;
576
+ if (ok) {
577
+ this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.ok') : 'Copied', 'success');
578
+ return;
579
+ }
580
+ this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.fail') : 'Copy failed', 'error');
581
+ },
582
+
583
+ normalizeSessionMessage(message) {
584
+ const fallback = {
585
+ role: 'assistant',
586
+ normalizedRole: 'assistant',
587
+ roleLabel: 'Assistant',
588
+ text: typeof message === 'string' ? message : '',
589
+ timestamp: ''
590
+ };
591
+ const safeMessage = message && typeof message === 'object' ? message : fallback;
592
+ const normalizedRole = normalizeSessionMessageRole(
593
+ safeMessage.normalizedRole || safeMessage.role
594
+ );
595
+ const roleLabel = normalizedRole === 'user'
596
+ ? 'User'
597
+ : (normalizedRole === 'system' ? 'System' : 'Assistant');
598
+ return {
599
+ ...safeMessage,
600
+ role: normalizedRole,
601
+ normalizedRole,
602
+ roleLabel
603
+ };
604
+ },
605
+
606
+ getRecordKey(message) {
607
+ if (!message || !Number.isInteger(message.recordLineIndex) || message.recordLineIndex < 0) {
608
+ return '';
609
+ }
610
+ return String(message.recordLineIndex);
611
+ },
612
+
613
+ getRecordRenderKey(message, idx) {
614
+ const recordKey = this.getRecordKey(message);
615
+ if (recordKey) {
616
+ return `record-${recordKey}`;
617
+ }
618
+ return `record-fallback-${idx}-${message && message.timestamp ? message.timestamp : ''}`;
619
+ },
620
+
621
+ syncActiveSessionMessageCount(messageCount) {
622
+ if (!Number.isFinite(messageCount) || messageCount < 0) return;
623
+ if (this.activeSession) {
624
+ this.activeSession.messageCount = messageCount;
625
+ }
626
+ const activeKey = this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
627
+ if (!activeKey) return;
628
+ const matched = this.sessionsList.find(item => this.getSessionExportKey(item) === activeKey);
629
+ if (matched) {
630
+ matched.messageCount = messageCount;
631
+ }
632
+ },
633
+
634
+ cancelScheduledSessionListMessageCountHydrate() {
635
+ const handle = this.__sessionListMessageCountHydrateHandle || null;
636
+ if (!handle) return;
637
+ if (typeof this.cancelIdleTask === 'function') {
638
+ this.cancelIdleTask(handle);
639
+ }
640
+ this.__sessionListMessageCountHydrateHandle = null;
641
+ },
642
+
643
+ resetSessionListMessageCountHydrate() {
644
+ this.cancelScheduledSessionListMessageCountHydrate();
645
+ this.__sessionListMessageCountHydrateInFlight = false;
646
+ this.__sessionListMessageCountHydrateLastScheduleAt = 0;
647
+ this.__sessionListMessageCountHydrateLastAttemptAtMap = {};
648
+ this.sessionListMessageCountHydrateRequestSeq = (Number(this.sessionListMessageCountHydrateRequestSeq) || 0) + 1;
649
+ },
650
+
651
+ scheduleSessionListMessageCountHydrate() {
652
+ if (this.mainTab !== 'sessions' || !this.sessionListRenderEnabled) {
653
+ return;
654
+ }
655
+ const now = Date.now();
656
+ const lastAt = Number(this.__sessionListMessageCountHydrateLastScheduleAt || 0);
657
+ if ((now - lastAt) < 120) {
658
+ return;
659
+ }
660
+ this.__sessionListMessageCountHydrateLastScheduleAt = now;
661
+ this.cancelScheduledSessionListMessageCountHydrate();
662
+ const run = () => {
663
+ this.__sessionListMessageCountHydrateHandle = null;
664
+ void this.hydrateVisibleSessionListMessageCounts();
665
+ };
666
+ if (typeof this.scheduleIdleTask === 'function') {
667
+ this.__sessionListMessageCountHydrateHandle = this.scheduleIdleTask(run, 160);
668
+ return;
669
+ }
670
+ if (typeof this.scheduleAfterFrame === 'function') {
671
+ this.scheduleAfterFrame(run);
672
+ return;
673
+ }
674
+ run();
675
+ },
676
+
677
+ async hydrateVisibleSessionListMessageCounts() {
678
+ if (this.__sessionListMessageCountHydrateInFlight) {
679
+ return;
680
+ }
681
+ if (this.mainTab !== 'sessions' || !this.sessionListRenderEnabled) {
682
+ return;
683
+ }
684
+
685
+ const visible = Array.isArray(this.visibleSessionsList) ? this.visibleSessionsList : [];
686
+ if (!visible.length) return;
687
+
688
+ const now = Date.now();
689
+ const lastAttemptAtMap = (this.__sessionListMessageCountHydrateLastAttemptAtMap && typeof this.__sessionListMessageCountHydrateLastAttemptAtMap === 'object')
690
+ ? this.__sessionListMessageCountHydrateLastAttemptAtMap
691
+ : {};
692
+ const targets = [];
693
+ for (const session of visible) {
694
+ if (!session || typeof session !== 'object') continue;
695
+ const messageCountRaw = Number(session.messageCount);
696
+ const shouldHydrate = !Number.isFinite(messageCountRaw) || messageCountRaw === 0;
697
+ if (!shouldHydrate) continue;
698
+ const key = this.getSessionExportKey(session);
699
+ if (!key) continue;
700
+ const lastAttempt = Number(lastAttemptAtMap[key] || 0);
701
+ if ((now - lastAttempt) < 5000) {
702
+ continue;
703
+ }
704
+ lastAttemptAtMap[key] = now;
705
+ targets.push({
706
+ source: session.source,
707
+ sessionId: session.sessionId,
708
+ filePath: session.filePath
709
+ });
710
+ if (targets.length >= 32) {
711
+ break;
712
+ }
713
+ }
714
+ this.__sessionListMessageCountHydrateLastAttemptAtMap = lastAttemptAtMap;
715
+ if (!targets.length) return;
716
+
717
+ const requestSeq = (Number(this.sessionListMessageCountHydrateRequestSeq) || 0) + 1;
718
+ this.sessionListMessageCountHydrateRequestSeq = requestSeq;
719
+ this.__sessionListMessageCountHydrateInFlight = true;
720
+ try {
721
+ const res = await api('session-message-counts', {
722
+ items: targets,
723
+ limit: targets.length
724
+ });
725
+ if (requestSeq !== Number(this.sessionListMessageCountHydrateRequestSeq || 0)) {
726
+ return;
727
+ }
728
+ if (!res || res.error || !Array.isArray(res.items)) {
729
+ return;
730
+ }
731
+ const byKey = new Map();
732
+ for (const item of res.items) {
733
+ if (!item || typeof item !== 'object') continue;
734
+ const key = typeof item.key === 'string' ? item.key : '';
735
+ if (!key) continue;
736
+ const messageCount = Number(item.messageCount);
737
+ if (!Number.isFinite(messageCount) || messageCount < 0) continue;
738
+ byKey.set(key, Math.floor(messageCount));
739
+ }
740
+ if (!byKey.size) {
741
+ return;
742
+ }
743
+ const sessions = Array.isArray(this.sessionsList) ? this.sessionsList : [];
744
+ const sessionMap = new Map(sessions.map((session) => [this.getSessionExportKey(session), session]));
745
+ for (const [key, count] of byKey.entries()) {
746
+ const matched = sessionMap.get(key);
747
+ if (matched) {
748
+ matched.messageCount = count;
749
+ }
750
+ if (this.activeSession && this.getSessionExportKey(this.activeSession) === key) {
751
+ this.activeSession.messageCount = count;
752
+ }
753
+ }
754
+ } catch (_) {
755
+ return;
756
+ } finally {
757
+ if (requestSeq === Number(this.sessionListMessageCountHydrateRequestSeq || 0)) {
758
+ this.__sessionListMessageCountHydrateInFlight = false;
759
+ }
760
+ }
761
+ },
762
+
763
+ invalidateSessionsUsageData(options = {}) {
764
+ this.sessionsUsageLoadedOnce = false;
765
+ this.sessionsUsageLoadedLimit = 0;
766
+ this.sessionsUsageError = '';
767
+ if (options.preserveList !== true) {
768
+ this.sessionsUsageList = [];
769
+ }
770
+ },
771
+
772
+ setSessionsUsageTimeRange(nextRange) {
773
+ const normalized = typeof nextRange === 'string' ? nextRange.trim().toLowerCase() : '';
774
+ const range = normalized === 'all' ? 'all' : (normalized === '30d' ? '30d' : '7d');
775
+ this.sessionsUsageTimeRange = range;
776
+ try { localStorage.setItem('sessionsUsageTimeRange', range); } catch (_) {}
777
+ if (range === 'all') {
778
+ this.sessionsUsageCompareEnabled = false;
779
+ }
780
+ void this.loadSessionsUsage({ range });
781
+ },
782
+
783
+ toggleSessionsUsageCompare() {
784
+ if (this.sessionsUsageTimeRange === 'all') {
785
+ this.sessionsUsageCompareEnabled = false;
786
+ return;
787
+ }
788
+ this.sessionsUsageCompareEnabled = !this.sessionsUsageCompareEnabled;
789
+ const range = typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '7d';
790
+ void this.loadSessionsUsage({
791
+ range,
792
+ limit: this.sessionsUsageCompareEnabled ? 2000 : undefined
793
+ });
794
+ },
795
+
796
+ selectSessionsUsageDay(dayKey) {
797
+ const normalized = typeof dayKey === 'string' ? dayKey.trim() : '';
798
+ this.sessionsUsageSelectedDayKey = normalized;
799
+ },
800
+
801
+ clearSessionsUsageDay() {
802
+ this.sessionsUsageSelectedDayKey = '';
803
+ },
804
+
805
+ async loadSessionsUsage(options = {}) {
806
+ if (this.sessionsUsageLoading) return;
807
+ const normalizedRange = typeof options.range === 'string'
808
+ ? options.range.trim().toLowerCase()
809
+ : (typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '');
810
+ const range = normalizedRange === 'all' ? 'all' : (normalizedRange === '30d' ? '30d' : '7d');
811
+ const defaultLimit = range === 'all' ? 2000 : (range === '30d' ? 1200 : 600);
812
+ const rawLimit = Number(options.limit);
813
+ const compareBoost = this.sessionsUsageCompareEnabled && range !== 'all'
814
+ ? 2000
815
+ : defaultLimit;
816
+ const limit = Number.isFinite(rawLimit)
817
+ ? Math.max(1, Math.min(rawLimit, 2000))
818
+ : compareBoost;
819
+ const loadedLimit = Number(this.sessionsUsageLoadedLimit || 0);
820
+ if (this.sessionsUsageLoadedOnce && !options.forceRefresh && loadedLimit >= limit) {
821
+ return;
822
+ }
823
+ this.sessionsUsageLoading = true;
824
+ this.sessionsUsageError = '';
825
+ let loadSucceeded = false;
826
+ try {
827
+ const res = await api('list-sessions-usage', {
828
+ source: 'all',
829
+ limit,
830
+ forceRefresh: !!options.forceRefresh
831
+ });
832
+ if (res.error) {
833
+ this.sessionsUsageError = res.error;
834
+ this.showMessage(res.error, 'error');
835
+ return;
836
+ }
837
+ this.sessionsUsageList = Array.isArray(res.sessions) ? res.sessions : [];
838
+ loadSucceeded = true;
839
+ } catch (e) {
840
+ this.sessionsUsageError = '加载 usage 统计失败';
841
+ this.showMessage('加载 usage 统计失败', 'error');
842
+ } finally {
843
+ this.sessionsUsageLoading = false;
844
+ if (loadSucceeded) {
845
+ this.sessionsUsageLoadedOnce = true;
846
+ this.sessionsUsageLoadedLimit = limit;
847
+ if (!this.sessionsUsageSelectedDayKey && Array.isArray(this.sessionUsageDailyTableRows) && this.sessionUsageDailyTableRows.length > 0) {
848
+ this.sessionsUsageSelectedDayKey = this.sessionUsageDailyTableRows[0].key;
849
+ }
850
+ }
851
+ }
852
+ },
853
+
854
+ async loadSessions(options = {}) {
855
+ this.resetSessionListMessageCountHydrate();
856
+ const result = await loadSessionsHelper.call(this, api, options || {});
857
+ this.pruneSessionPinnedMap(this.sessionsList);
858
+ return result;
859
+ },
860
+
861
+ async selectSession(session) {
862
+ if (!session) {
863
+ emitSessionLoadNativeDialog(this, 'selectSession:skip-empty');
864
+ return;
865
+ }
866
+ emitSessionLoadNativeDialog(
867
+ this,
868
+ 'selectSession:start',
869
+ `sessionId=${session.sessionId || ''}\nsource=${session.source || ''}`
870
+ );
871
+ const isSameSession = this.activeSession
872
+ && this.getSessionExportKey(this.activeSession) === this.getSessionExportKey(session);
873
+ if (isSameSession) {
874
+ emitSessionLoadNativeDialog(this, 'selectSession:same-session', `sessionId=${session.sessionId || ''}`);
875
+ if (this.sessionDetailLoading) {
876
+ emitSessionLoadNativeDialog(this, 'selectSession:skip-detail-loading', `sessionId=${session.sessionId || ''}`);
877
+ return;
878
+ }
879
+ const currentMessages = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages : [];
880
+ if (currentMessages.length > 0) {
881
+ emitSessionLoadNativeDialog(
882
+ this,
883
+ 'selectSession:skip-existing-messages',
884
+ `sessionId=${session.sessionId || ''}\nmessages=${currentMessages.length}`
885
+ );
886
+ return;
887
+ }
888
+ if (typeof this.scheduleAfterFrame === 'function') {
889
+ const selectedSession = this.activeSession;
890
+ emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
891
+ this.scheduleAfterFrame(() => {
892
+ if (this.activeSession !== selectedSession) return;
893
+ void this.loadActiveSessionDetail();
894
+ });
895
+ return;
896
+ }
897
+ emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
898
+ await this.loadActiveSessionDetail();
899
+ return;
900
+ }
901
+ this.activeSession = session;
902
+ emitSessionLoadNativeDialog(this, 'selectSession:activate', `sessionId=${session.sessionId || ''}`);
903
+ if (typeof this.expandVisibleSessionList === 'function') {
904
+ this.expandVisibleSessionList(0, { ensureActive: true });
905
+ }
906
+ this.activeSessionMessages = [];
907
+ this.resetSessionDetailPagination();
908
+ this.resetSessionPreviewMessageRender();
909
+ this.activeSessionDetailError = '';
910
+ this.activeSessionDetailClipped = false;
911
+ this.cancelSessionTimelineSync();
912
+ this.sessionTimelineActiveKey = '';
913
+ this.clearSessionTimelineRefs();
914
+ if (typeof this.scheduleAfterFrame === 'function') {
915
+ const selectedSession = this.activeSession;
916
+ emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
917
+ this.scheduleAfterFrame(() => {
918
+ if (this.activeSession !== selectedSession) return;
919
+ void this.loadActiveSessionDetail();
920
+ });
921
+ return;
922
+ }
923
+ emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
924
+ await this.loadActiveSessionDetail();
925
+ },
926
+
927
+ async loadSessionStandalonePlain() {
928
+ if (!this.activeSession) {
929
+ this.sessionStandaloneRequestSeq += 1;
930
+ this.sessionStandaloneLoading = false;
931
+ this.sessionStandaloneText = '';
932
+ this.sessionStandaloneTitle = '会话';
933
+ this.sessionStandaloneSourceLabel = '';
934
+ this.sessionStandaloneError = '';
935
+ return;
936
+ }
937
+
938
+ const requestSeq = ++this.sessionStandaloneRequestSeq;
939
+ const sessionSnapshot = this.activeSession;
940
+ this.sessionStandaloneLoading = true;
941
+ this.sessionStandaloneError = '';
942
+ try {
943
+ const res = await api('session-plain', {
944
+ source: sessionSnapshot.source,
945
+ sessionId: sessionSnapshot.sessionId,
946
+ filePath: sessionSnapshot.filePath,
947
+ maxMessages: sessionSnapshot.maxMessages || 50
948
+ });
949
+
950
+ if (requestSeq !== this.sessionStandaloneRequestSeq) {
951
+ return;
952
+ }
953
+
954
+ if (res.error) {
955
+ this.sessionStandaloneText = '';
956
+ this.sessionStandaloneError = res.error;
957
+ return;
958
+ }
959
+
960
+ this.sessionStandaloneSourceLabel = res.sourceLabel || sessionSnapshot.sourceLabel || '';
961
+ this.sessionStandaloneTitle = res.sessionId || sessionSnapshot.title || '会话';
962
+ this.sessionStandaloneText = typeof res.text === 'string' ? res.text : '';
963
+ } catch (e) {
964
+ if (requestSeq !== this.sessionStandaloneRequestSeq) {
965
+ return;
966
+ }
967
+ this.sessionStandaloneText = '';
968
+ this.sessionStandaloneError = '加载会话内容失败: ' + e.message;
969
+ } finally {
970
+ if (requestSeq === this.sessionStandaloneRequestSeq) {
971
+ this.sessionStandaloneLoading = false;
972
+ }
973
+ }
974
+ },
975
+
976
+ async loadActiveSessionDetail(options = {}) {
977
+ const result = await loadActiveSessionDetailHelper.call(this, api, options);
978
+ if (this.mainTab === 'sessions' && typeof this.scheduleSessionListMessageCountHydrate === 'function') {
979
+ this.scheduleSessionListMessageCountHydrate();
980
+ }
981
+ return result;
982
+ }
983
+ };
984
+ }