codexmate 0.0.40 → 0.0.41

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