codexmate 0.0.25 → 0.0.26

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 (135) hide show
  1. package/README.md +416 -413
  2. package/README.zh.md +349 -346
  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 +1079 -1079
  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 +997 -997
  13. package/cli/openclaw-config.js +629 -629
  14. package/cli/session-convert-args.js +65 -0
  15. package/cli/session-convert-io.js +82 -0
  16. package/cli/session-convert.js +43 -0
  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 +15218 -14736
  23. package/lib/automation.js +404 -404
  24. package/lib/cli-file-utils.js +151 -151
  25. package/lib/cli-models-utils.js +379 -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 +74 -74
  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 +619 -619
  44. package/plugins/prompt-templates/overview.mjs +90 -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 -612
  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.mjs +5 -5
  54. package/web-ui/logic.runtime.mjs +128 -128
  55. package/web-ui/logic.session-convert.mjs +70 -0
  56. package/web-ui/logic.sessions.mjs +709 -614
  57. package/web-ui/modules/api.mjs +90 -90
  58. package/web-ui/modules/app.computed.dashboard.mjs +171 -128
  59. package/web-ui/modules/app.computed.index.mjs +17 -17
  60. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  61. package/web-ui/modules/app.computed.session.mjs +946 -670
  62. package/web-ui/modules/app.constants.mjs +15 -15
  63. package/web-ui/modules/app.methods.agents.mjs +632 -632
  64. package/web-ui/modules/app.methods.claude-config.mjs +179 -174
  65. package/web-ui/modules/app.methods.codex-config.mjs +860 -784
  66. package/web-ui/modules/app.methods.index.mjs +92 -92
  67. package/web-ui/modules/app.methods.install.mjs +205 -205
  68. package/web-ui/modules/app.methods.navigation.mjs +743 -695
  69. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  70. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  71. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  72. package/web-ui/modules/app.methods.providers.mjs +404 -404
  73. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  74. package/web-ui/modules/app.methods.session-actions.mjs +596 -544
  75. package/web-ui/modules/app.methods.session-browser.mjs +985 -722
  76. package/web-ui/modules/app.methods.session-timeline.mjs +479 -448
  77. package/web-ui/modules/app.methods.session-trash.mjs +424 -424
  78. package/web-ui/modules/app.methods.startup-claude.mjs +522 -417
  79. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  80. package/web-ui/modules/config-mode.computed.mjs +124 -124
  81. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  82. package/web-ui/modules/i18n.dict.mjs +2113 -2055
  83. package/web-ui/modules/i18n.mjs +56 -56
  84. package/web-ui/modules/plugins.computed.mjs +3 -3
  85. package/web-ui/modules/plugins.methods.mjs +3 -3
  86. package/web-ui/modules/plugins.storage.mjs +11 -11
  87. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  88. package/web-ui/modules/skills.computed.mjs +107 -107
  89. package/web-ui/modules/skills.methods.mjs +481 -481
  90. package/web-ui/partials/index/layout-footer.html +13 -13
  91. package/web-ui/partials/index/layout-header.html +475 -475
  92. package/web-ui/partials/index/modal-config-template-agents.html +174 -174
  93. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  94. package/web-ui/partials/index/modal-health-check.html +45 -45
  95. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  96. package/web-ui/partials/index/modal-skills.html +200 -200
  97. package/web-ui/partials/index/modals-basic.html +165 -165
  98. package/web-ui/partials/index/panel-config-claude.html +184 -179
  99. package/web-ui/partials/index/panel-config-codex.html +283 -283
  100. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  101. package/web-ui/partials/index/panel-dashboard.html +186 -186
  102. package/web-ui/partials/index/panel-docs.html +147 -147
  103. package/web-ui/partials/index/panel-market.html +177 -177
  104. package/web-ui/partials/index/panel-orchestration.html +391 -391
  105. package/web-ui/partials/index/panel-plugins.html +279 -279
  106. package/web-ui/partials/index/panel-sessions.html +326 -303
  107. package/web-ui/partials/index/panel-settings.html +258 -258
  108. package/web-ui/partials/index/panel-usage.html +342 -361
  109. package/web-ui/res/json5.min.js +1 -1
  110. package/web-ui/res/vue.global.prod.js +13 -13
  111. package/web-ui/session-helpers.mjs +576 -573
  112. package/web-ui/source-bundle.cjs +233 -233
  113. package/web-ui/styles/base-theme.css +268 -264
  114. package/web-ui/styles/controls-forms.css +423 -423
  115. package/web-ui/styles/dashboard.css +274 -274
  116. package/web-ui/styles/docs-panel.css +247 -247
  117. package/web-ui/styles/feedback.css +108 -108
  118. package/web-ui/styles/health-check-dialog.css +144 -144
  119. package/web-ui/styles/layout-shell.css +603 -603
  120. package/web-ui/styles/modals-core.css +464 -464
  121. package/web-ui/styles/navigation-panels.css +390 -390
  122. package/web-ui/styles/openclaw-structured.css +266 -266
  123. package/web-ui/styles/plugins-panel.css +523 -523
  124. package/web-ui/styles/responsive.css +454 -454
  125. package/web-ui/styles/sessions-list.css +415 -398
  126. package/web-ui/styles/sessions-preview.css +411 -411
  127. package/web-ui/styles/sessions-toolbar-trash.css +330 -268
  128. package/web-ui/styles/sessions-usage.css +945 -912
  129. package/web-ui/styles/settings-panel.css +166 -166
  130. package/web-ui/styles/skills-list.css +303 -303
  131. package/web-ui/styles/skills-market.css +406 -406
  132. package/web-ui/styles/task-orchestration.css +822 -822
  133. package/web-ui/styles/titles-cards.css +408 -408
  134. package/web-ui/styles.css +21 -21
  135. package/web-ui.html +17 -17
@@ -1,722 +1,985 @@
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
- restoreSessionFilterCache() {
258
- const urlState = readSessionsFilterUrlState();
259
- if (urlState) {
260
- applySessionsFilterUrlState(this, urlState);
261
- if (this.mainTab === 'sessions' && typeof this.loadSessions === 'function') {
262
- void this.loadSessions();
263
- }
264
- return;
265
- }
266
- const sourceCache = localStorage.getItem('codexmateSessionFilterSource');
267
- const pathCache = localStorage.getItem('codexmateSessionPathFilter');
268
- const cached = buildSessionFilterCacheState(sourceCache, pathCache);
269
- this.sessionFilterSource = cached.source;
270
- this.sessionPathFilter = cached.pathFilter;
271
- const queryCache = localStorage.getItem('codexmateSessionQuery');
272
- const roleCache = localStorage.getItem('codexmateSessionRoleFilter');
273
- const timeCache = localStorage.getItem('codexmateSessionTimePreset');
274
- this.sessionQuery = typeof queryCache === 'string' ? queryCache : '';
275
- this.sessionRoleFilter = normalizeSessionRoleFilter(roleCache);
276
- this.sessionTimePreset = normalizeSessionTimePreset(timeCache);
277
- this.refreshSessionPathOptions(this.sessionFilterSource);
278
- if (this.mainTab === 'sessions' && typeof this.loadSessions === 'function') {
279
- const shouldReload = cached.source !== 'all'
280
- || !!cached.pathFilter
281
- || !!(this.sessionQuery && isSessionQueryEnabled(cached.source))
282
- || (this.sessionRoleFilter && this.sessionRoleFilter !== 'all')
283
- || (this.sessionTimePreset && this.sessionTimePreset !== 'all');
284
- if (shouldReload) {
285
- void this.loadSessions();
286
- }
287
- }
288
- },
289
-
290
- persistSessionFilterCache() {
291
- const cached = buildSessionFilterCacheState(this.sessionFilterSource, this.sessionPathFilter);
292
- localStorage.setItem('codexmateSessionFilterSource', cached.source);
293
- if (cached.pathFilter) {
294
- localStorage.setItem('codexmateSessionPathFilter', cached.pathFilter);
295
- } else {
296
- localStorage.removeItem('codexmateSessionPathFilter');
297
- }
298
- if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
299
- localStorage.setItem('codexmateSessionQuery', this.sessionQuery);
300
- } else {
301
- localStorage.removeItem('codexmateSessionQuery');
302
- }
303
- localStorage.setItem('codexmateSessionRoleFilter', normalizeSessionRoleFilter(this.sessionRoleFilter));
304
- localStorage.setItem('codexmateSessionTimePreset', normalizeSessionTimePreset(this.sessionTimePreset));
305
- },
306
-
307
- normalizeSessionPinnedMap(raw) {
308
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
309
- return {};
310
- }
311
- const next = {};
312
- for (const [key, value] of Object.entries(raw)) {
313
- if (!key) continue;
314
- const numeric = Number(value);
315
- if (!Number.isFinite(numeric) || numeric <= 0) continue;
316
- next[key] = Math.floor(numeric);
317
- }
318
- return next;
319
- },
320
-
321
- restoreSessionPinnedMap() {
322
- const cached = localStorage.getItem('codexmateSessionPinnedMap');
323
- if (!cached) {
324
- this.sessionPinnedMap = {};
325
- return;
326
- }
327
- try {
328
- const parsed = JSON.parse(cached);
329
- this.sessionPinnedMap = this.normalizeSessionPinnedMap(parsed);
330
- } catch (_) {
331
- this.sessionPinnedMap = {};
332
- localStorage.removeItem('codexmateSessionPinnedMap');
333
- }
334
- },
335
-
336
- persistSessionPinnedMap() {
337
- const payload = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
338
- ? this.sessionPinnedMap
339
- : {};
340
- localStorage.setItem('codexmateSessionPinnedMap', JSON.stringify(payload));
341
- },
342
-
343
- shouldPruneSessionPinnedMap(sessions = this.sessionsList) {
344
- if (!Array.isArray(sessions) || sessions.length === 0) {
345
- return false;
346
- }
347
- if (this.sessionFilterSource !== 'all') {
348
- return false;
349
- }
350
- if (this.sessionPathFilter) {
351
- return false;
352
- }
353
- if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
354
- return false;
355
- }
356
- if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') {
357
- return false;
358
- }
359
- if (this.sessionTimePreset && this.sessionTimePreset !== 'all') {
360
- return false;
361
- }
362
- return true;
363
- },
364
-
365
- pruneSessionPinnedMap(sessions = this.sessionsList) {
366
- const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
367
- ? this.sessionPinnedMap
368
- : {};
369
- const list = Array.isArray(sessions) ? sessions : [];
370
- if (Object.keys(current).length === 0 || !this.shouldPruneSessionPinnedMap(list)) {
371
- return;
372
- }
373
- const validKeys = new Set(list.map((session) => this.getSessionExportKey(session)).filter(Boolean));
374
- const next = {};
375
- let changed = false;
376
- for (const [key, value] of Object.entries(current)) {
377
- if (!validKeys.has(key)) {
378
- changed = true;
379
- continue;
380
- }
381
- next[key] = value;
382
- }
383
- if (!changed) {
384
- return;
385
- }
386
- this.sessionPinnedMap = next;
387
- this.persistSessionPinnedMap();
388
- },
389
-
390
- getSessionPinTimestamp(session) {
391
- if (!session) return 0;
392
- const key = this.getSessionExportKey(session);
393
- if (!key) return 0;
394
- const raw = this.sessionPinnedMap && this.sessionPinnedMap[key];
395
- const numeric = Number(raw);
396
- return Number.isFinite(numeric) && numeric > 0 ? Math.floor(numeric) : 0;
397
- },
398
-
399
- isSessionPinned(session) {
400
- return this.getSessionPinTimestamp(session) > 0;
401
- },
402
-
403
- toggleSessionPin(session) {
404
- if (!session) return;
405
- const key = this.getSessionExportKey(session);
406
- if (!key) return;
407
- const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
408
- ? this.sessionPinnedMap
409
- : {};
410
- const next = { ...current };
411
- if (next[key]) {
412
- delete next[key];
413
- } else {
414
- next[key] = Date.now();
415
- }
416
- this.sessionPinnedMap = next;
417
- this.persistSessionPinnedMap();
418
- },
419
-
420
- removeSessionPin(session) {
421
- if (!session) return;
422
- const key = this.getSessionExportKey(session);
423
- if (!key) return;
424
- const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
425
- ? this.sessionPinnedMap
426
- : {};
427
- if (!current[key]) return;
428
- const next = { ...current };
429
- delete next[key];
430
- this.sessionPinnedMap = next;
431
- this.persistSessionPinnedMap();
432
- },
433
-
434
- async onSessionSourceChange(event) {
435
- const rawValue = event && event.target && typeof event.target.value === 'string'
436
- ? event.target.value
437
- : this.sessionFilterSource;
438
- const cached = buildSessionFilterCacheState(rawValue, this.sessionPathFilter);
439
- this.sessionFilterSource = cached.source;
440
- this.refreshSessionPathOptions(this.sessionFilterSource);
441
- this.persistSessionFilterCache();
442
- syncSessionsFilterUrl(this);
443
- await this.loadSessions();
444
- },
445
-
446
- async onSessionPathFilterChange() {
447
- this.persistSessionFilterCache();
448
- syncSessionsFilterUrl(this);
449
- await this.loadSessions();
450
- },
451
-
452
- async onSessionFilterChange() {
453
- this.persistSessionFilterCache();
454
- syncSessionsFilterUrl(this);
455
- await this.loadSessions();
456
- },
457
-
458
- async clearSessionFilters() {
459
- this.sessionFilterSource = 'all';
460
- this.sessionPathFilter = '';
461
- this.sessionQuery = '';
462
- this.sessionRoleFilter = 'all';
463
- this.sessionTimePreset = 'all';
464
- this.persistSessionFilterCache();
465
- syncSessionsFilterUrl(this);
466
- await this.onSessionSourceChange();
467
- },
468
-
469
- async copySessionsFilterShareUrl() {
470
- const url = buildSessionsFilterShareUrl(this);
471
- if (!url) {
472
- this.showMessage(typeof this.t === 'function' ? this.t('sessions.filters.urlBuildFail') : 'Failed to build link', 'error');
473
- return;
474
- }
475
- try {
476
- if (navigator.clipboard && window.isSecureContext) {
477
- await navigator.clipboard.writeText(url);
478
- this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.ok') : 'Copied', 'success');
479
- return;
480
- }
481
- } catch (_) {}
482
- const ok = typeof this.fallbackCopyText === 'function' ? this.fallbackCopyText(url) : false;
483
- if (ok) {
484
- this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.ok') : 'Copied', 'success');
485
- return;
486
- }
487
- this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.fail') : 'Copy failed', 'error');
488
- },
489
-
490
- normalizeSessionMessage(message) {
491
- const fallback = {
492
- role: 'assistant',
493
- normalizedRole: 'assistant',
494
- roleLabel: 'Assistant',
495
- text: typeof message === 'string' ? message : '',
496
- timestamp: ''
497
- };
498
- const safeMessage = message && typeof message === 'object' ? message : fallback;
499
- const normalizedRole = normalizeSessionMessageRole(
500
- safeMessage.normalizedRole || safeMessage.role
501
- );
502
- const roleLabel = normalizedRole === 'user'
503
- ? 'User'
504
- : (normalizedRole === 'system' ? 'System' : 'Assistant');
505
- return {
506
- ...safeMessage,
507
- role: normalizedRole,
508
- normalizedRole,
509
- roleLabel
510
- };
511
- },
512
-
513
- getRecordKey(message) {
514
- if (!message || !Number.isInteger(message.recordLineIndex) || message.recordLineIndex < 0) {
515
- return '';
516
- }
517
- return String(message.recordLineIndex);
518
- },
519
-
520
- getRecordRenderKey(message, idx) {
521
- const recordKey = this.getRecordKey(message);
522
- if (recordKey) {
523
- return `record-${recordKey}`;
524
- }
525
- return `record-fallback-${idx}-${message && message.timestamp ? message.timestamp : ''}`;
526
- },
527
-
528
- syncActiveSessionMessageCount(messageCount) {
529
- if (!Number.isFinite(messageCount) || messageCount < 0) return;
530
- if (this.activeSession) {
531
- this.activeSession.messageCount = messageCount;
532
- }
533
- const activeKey = this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
534
- if (!activeKey) return;
535
- const matched = this.sessionsList.find(item => this.getSessionExportKey(item) === activeKey);
536
- if (matched) {
537
- matched.messageCount = messageCount;
538
- }
539
- },
540
-
541
- invalidateSessionsUsageData(options = {}) {
542
- this.sessionsUsageLoadedOnce = false;
543
- this.sessionsUsageLoadedLimit = 0;
544
- this.sessionsUsageError = '';
545
- if (options.preserveList !== true) {
546
- this.sessionsUsageList = [];
547
- }
548
- },
549
-
550
- setSessionsUsageTimeRange(nextRange) {
551
- const normalized = typeof nextRange === 'string' ? nextRange.trim().toLowerCase() : '';
552
- const range = normalized === 'all' ? 'all' : (normalized === '30d' ? '30d' : '7d');
553
- this.sessionsUsageTimeRange = range;
554
- void this.loadSessionsUsage({ range });
555
- },
556
-
557
- async loadSessionsUsage(options = {}) {
558
- if (this.sessionsUsageLoading) return;
559
- const normalizedRange = typeof options.range === 'string'
560
- ? options.range.trim().toLowerCase()
561
- : (typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '');
562
- const range = normalizedRange === 'all' ? 'all' : (normalizedRange === '30d' ? '30d' : '7d');
563
- const defaultLimit = range === 'all' ? 2000 : (range === '30d' ? 1200 : 600);
564
- const rawLimit = Number(options.limit);
565
- const limit = Number.isFinite(rawLimit) ? Math.max(1, Math.min(rawLimit, 2000)) : defaultLimit;
566
- const loadedLimit = Number(this.sessionsUsageLoadedLimit || 0);
567
- if (this.sessionsUsageLoadedOnce && !options.forceRefresh && loadedLimit >= limit) {
568
- return;
569
- }
570
- this.sessionsUsageLoading = true;
571
- this.sessionsUsageError = '';
572
- let loadSucceeded = false;
573
- try {
574
- const res = await api('list-sessions-usage', {
575
- source: 'all',
576
- limit,
577
- forceRefresh: !!options.forceRefresh
578
- });
579
- if (res.error) {
580
- this.sessionsUsageError = res.error;
581
- this.showMessage(res.error, 'error');
582
- return;
583
- }
584
- this.sessionsUsageList = Array.isArray(res.sessions) ? res.sessions : [];
585
- loadSucceeded = true;
586
- } catch (e) {
587
- this.sessionsUsageError = '加载 usage 统计失败';
588
- this.showMessage('加载 usage 统计失败', 'error');
589
- } finally {
590
- this.sessionsUsageLoading = false;
591
- if (loadSucceeded) {
592
- this.sessionsUsageLoadedOnce = true;
593
- this.sessionsUsageLoadedLimit = limit;
594
- }
595
- }
596
- },
597
-
598
- async loadSessions(options = {}) {
599
- const result = await loadSessionsHelper.call(this, api, options || {});
600
- this.pruneSessionPinnedMap(this.sessionsList);
601
- return result;
602
- },
603
-
604
- async selectSession(session) {
605
- if (!session) {
606
- emitSessionLoadNativeDialog(this, 'selectSession:skip-empty');
607
- return;
608
- }
609
- emitSessionLoadNativeDialog(
610
- this,
611
- 'selectSession:start',
612
- `sessionId=${session.sessionId || ''}\nsource=${session.source || ''}`
613
- );
614
- const isSameSession = this.activeSession
615
- && this.getSessionExportKey(this.activeSession) === this.getSessionExportKey(session);
616
- if (isSameSession) {
617
- emitSessionLoadNativeDialog(this, 'selectSession:same-session', `sessionId=${session.sessionId || ''}`);
618
- if (this.sessionDetailLoading) {
619
- emitSessionLoadNativeDialog(this, 'selectSession:skip-detail-loading', `sessionId=${session.sessionId || ''}`);
620
- return;
621
- }
622
- const currentMessages = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages : [];
623
- if (currentMessages.length > 0) {
624
- emitSessionLoadNativeDialog(
625
- this,
626
- 'selectSession:skip-existing-messages',
627
- `sessionId=${session.sessionId || ''}\nmessages=${currentMessages.length}`
628
- );
629
- return;
630
- }
631
- if (typeof this.scheduleAfterFrame === 'function') {
632
- const selectedSession = this.activeSession;
633
- emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
634
- this.scheduleAfterFrame(() => {
635
- if (this.activeSession !== selectedSession) return;
636
- void this.loadActiveSessionDetail();
637
- });
638
- return;
639
- }
640
- emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
641
- await this.loadActiveSessionDetail();
642
- return;
643
- }
644
- this.activeSession = session;
645
- emitSessionLoadNativeDialog(this, 'selectSession:activate', `sessionId=${session.sessionId || ''}`);
646
- if (typeof this.expandVisibleSessionList === 'function') {
647
- this.expandVisibleSessionList(0, { ensureActive: true });
648
- }
649
- this.activeSessionMessages = [];
650
- this.resetSessionDetailPagination();
651
- this.resetSessionPreviewMessageRender();
652
- this.activeSessionDetailError = '';
653
- this.activeSessionDetailClipped = false;
654
- this.cancelSessionTimelineSync();
655
- this.sessionTimelineActiveKey = '';
656
- this.clearSessionTimelineRefs();
657
- if (typeof this.scheduleAfterFrame === 'function') {
658
- const selectedSession = this.activeSession;
659
- emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
660
- this.scheduleAfterFrame(() => {
661
- if (this.activeSession !== selectedSession) return;
662
- void this.loadActiveSessionDetail();
663
- });
664
- return;
665
- }
666
- emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
667
- await this.loadActiveSessionDetail();
668
- },
669
-
670
- async loadSessionStandalonePlain() {
671
- if (!this.activeSession) {
672
- this.sessionStandaloneRequestSeq += 1;
673
- this.sessionStandaloneLoading = false;
674
- this.sessionStandaloneText = '';
675
- this.sessionStandaloneTitle = '会话';
676
- this.sessionStandaloneSourceLabel = '';
677
- this.sessionStandaloneError = '';
678
- return;
679
- }
680
-
681
- const requestSeq = ++this.sessionStandaloneRequestSeq;
682
- const sessionSnapshot = this.activeSession;
683
- this.sessionStandaloneLoading = true;
684
- this.sessionStandaloneError = '';
685
- try {
686
- const res = await api('session-plain', {
687
- source: sessionSnapshot.source,
688
- sessionId: sessionSnapshot.sessionId,
689
- filePath: sessionSnapshot.filePath
690
- });
691
-
692
- if (requestSeq !== this.sessionStandaloneRequestSeq) {
693
- return;
694
- }
695
-
696
- if (res.error) {
697
- this.sessionStandaloneText = '';
698
- this.sessionStandaloneError = res.error;
699
- return;
700
- }
701
-
702
- this.sessionStandaloneSourceLabel = res.sourceLabel || sessionSnapshot.sourceLabel || '';
703
- this.sessionStandaloneTitle = res.sessionId || sessionSnapshot.title || '会话';
704
- this.sessionStandaloneText = typeof res.text === 'string' ? res.text : '';
705
- } catch (e) {
706
- if (requestSeq !== this.sessionStandaloneRequestSeq) {
707
- return;
708
- }
709
- this.sessionStandaloneText = '';
710
- this.sessionStandaloneError = '加载会话内容失败: ' + e.message;
711
- } finally {
712
- if (requestSeq === this.sessionStandaloneRequestSeq) {
713
- this.sessionStandaloneLoading = false;
714
- }
715
- }
716
- },
717
-
718
- async loadActiveSessionDetail(options = {}) {
719
- return loadActiveSessionDetailHelper.call(this, api, options);
720
- }
721
- };
722
- }
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
+ if (range === 'all') {
782
+ this.sessionsUsageCompareEnabled = false;
783
+ }
784
+ void this.loadSessionsUsage({ range });
785
+ },
786
+
787
+ toggleSessionsUsageCompare() {
788
+ if (this.sessionsUsageTimeRange === 'all') {
789
+ this.sessionsUsageCompareEnabled = false;
790
+ return;
791
+ }
792
+ this.sessionsUsageCompareEnabled = !this.sessionsUsageCompareEnabled;
793
+ const range = typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '7d';
794
+ void this.loadSessionsUsage({
795
+ range,
796
+ limit: this.sessionsUsageCompareEnabled ? 2000 : undefined
797
+ });
798
+ },
799
+
800
+ selectSessionsUsageDay(dayKey) {
801
+ const normalized = typeof dayKey === 'string' ? dayKey.trim() : '';
802
+ this.sessionsUsageSelectedDayKey = normalized;
803
+ },
804
+
805
+ clearSessionsUsageDay() {
806
+ this.sessionsUsageSelectedDayKey = '';
807
+ },
808
+
809
+ async loadSessionsUsage(options = {}) {
810
+ if (this.sessionsUsageLoading) return;
811
+ const normalizedRange = typeof options.range === 'string'
812
+ ? options.range.trim().toLowerCase()
813
+ : (typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '');
814
+ const range = normalizedRange === 'all' ? 'all' : (normalizedRange === '30d' ? '30d' : '7d');
815
+ const defaultLimit = range === 'all' ? 2000 : (range === '30d' ? 1200 : 600);
816
+ const rawLimit = Number(options.limit);
817
+ const compareBoost = this.sessionsUsageCompareEnabled && range !== 'all'
818
+ ? 2000
819
+ : defaultLimit;
820
+ const limit = Number.isFinite(rawLimit)
821
+ ? Math.max(1, Math.min(rawLimit, 2000))
822
+ : compareBoost;
823
+ const loadedLimit = Number(this.sessionsUsageLoadedLimit || 0);
824
+ if (this.sessionsUsageLoadedOnce && !options.forceRefresh && loadedLimit >= limit) {
825
+ return;
826
+ }
827
+ this.sessionsUsageLoading = true;
828
+ this.sessionsUsageError = '';
829
+ let loadSucceeded = false;
830
+ try {
831
+ const res = await api('list-sessions-usage', {
832
+ source: 'all',
833
+ limit,
834
+ forceRefresh: !!options.forceRefresh
835
+ });
836
+ if (res.error) {
837
+ this.sessionsUsageError = res.error;
838
+ this.showMessage(res.error, 'error');
839
+ return;
840
+ }
841
+ this.sessionsUsageList = Array.isArray(res.sessions) ? res.sessions : [];
842
+ loadSucceeded = true;
843
+ } catch (e) {
844
+ this.sessionsUsageError = '加载 usage 统计失败';
845
+ this.showMessage('加载 usage 统计失败', 'error');
846
+ } finally {
847
+ this.sessionsUsageLoading = false;
848
+ if (loadSucceeded) {
849
+ this.sessionsUsageLoadedOnce = true;
850
+ this.sessionsUsageLoadedLimit = limit;
851
+ }
852
+ }
853
+ },
854
+
855
+ async loadSessions(options = {}) {
856
+ this.resetSessionListMessageCountHydrate();
857
+ const result = await loadSessionsHelper.call(this, api, options || {});
858
+ this.pruneSessionPinnedMap(this.sessionsList);
859
+ return result;
860
+ },
861
+
862
+ async selectSession(session) {
863
+ if (!session) {
864
+ emitSessionLoadNativeDialog(this, 'selectSession:skip-empty');
865
+ return;
866
+ }
867
+ emitSessionLoadNativeDialog(
868
+ this,
869
+ 'selectSession:start',
870
+ `sessionId=${session.sessionId || ''}\nsource=${session.source || ''}`
871
+ );
872
+ const isSameSession = this.activeSession
873
+ && this.getSessionExportKey(this.activeSession) === this.getSessionExportKey(session);
874
+ if (isSameSession) {
875
+ emitSessionLoadNativeDialog(this, 'selectSession:same-session', `sessionId=${session.sessionId || ''}`);
876
+ if (this.sessionDetailLoading) {
877
+ emitSessionLoadNativeDialog(this, 'selectSession:skip-detail-loading', `sessionId=${session.sessionId || ''}`);
878
+ return;
879
+ }
880
+ const currentMessages = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages : [];
881
+ if (currentMessages.length > 0) {
882
+ emitSessionLoadNativeDialog(
883
+ this,
884
+ 'selectSession:skip-existing-messages',
885
+ `sessionId=${session.sessionId || ''}\nmessages=${currentMessages.length}`
886
+ );
887
+ return;
888
+ }
889
+ if (typeof this.scheduleAfterFrame === 'function') {
890
+ const selectedSession = this.activeSession;
891
+ emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
892
+ this.scheduleAfterFrame(() => {
893
+ if (this.activeSession !== selectedSession) return;
894
+ void this.loadActiveSessionDetail();
895
+ });
896
+ return;
897
+ }
898
+ emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
899
+ await this.loadActiveSessionDetail();
900
+ return;
901
+ }
902
+ this.activeSession = session;
903
+ emitSessionLoadNativeDialog(this, 'selectSession:activate', `sessionId=${session.sessionId || ''}`);
904
+ if (typeof this.expandVisibleSessionList === 'function') {
905
+ this.expandVisibleSessionList(0, { ensureActive: true });
906
+ }
907
+ this.activeSessionMessages = [];
908
+ this.resetSessionDetailPagination();
909
+ this.resetSessionPreviewMessageRender();
910
+ this.activeSessionDetailError = '';
911
+ this.activeSessionDetailClipped = false;
912
+ this.cancelSessionTimelineSync();
913
+ this.sessionTimelineActiveKey = '';
914
+ this.clearSessionTimelineRefs();
915
+ if (typeof this.scheduleAfterFrame === 'function') {
916
+ const selectedSession = this.activeSession;
917
+ emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
918
+ this.scheduleAfterFrame(() => {
919
+ if (this.activeSession !== selectedSession) return;
920
+ void this.loadActiveSessionDetail();
921
+ });
922
+ return;
923
+ }
924
+ emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
925
+ await this.loadActiveSessionDetail();
926
+ },
927
+
928
+ async loadSessionStandalonePlain() {
929
+ if (!this.activeSession) {
930
+ this.sessionStandaloneRequestSeq += 1;
931
+ this.sessionStandaloneLoading = false;
932
+ this.sessionStandaloneText = '';
933
+ this.sessionStandaloneTitle = '会话';
934
+ this.sessionStandaloneSourceLabel = '';
935
+ this.sessionStandaloneError = '';
936
+ return;
937
+ }
938
+
939
+ const requestSeq = ++this.sessionStandaloneRequestSeq;
940
+ const sessionSnapshot = this.activeSession;
941
+ this.sessionStandaloneLoading = true;
942
+ this.sessionStandaloneError = '';
943
+ try {
944
+ const res = await api('session-plain', {
945
+ source: sessionSnapshot.source,
946
+ sessionId: sessionSnapshot.sessionId,
947
+ filePath: sessionSnapshot.filePath,
948
+ maxMessages: sessionSnapshot.maxMessages || 50
949
+ });
950
+
951
+ if (requestSeq !== this.sessionStandaloneRequestSeq) {
952
+ return;
953
+ }
954
+
955
+ if (res.error) {
956
+ this.sessionStandaloneText = '';
957
+ this.sessionStandaloneError = res.error;
958
+ return;
959
+ }
960
+
961
+ this.sessionStandaloneSourceLabel = res.sourceLabel || sessionSnapshot.sourceLabel || '';
962
+ this.sessionStandaloneTitle = res.sessionId || sessionSnapshot.title || '会话';
963
+ this.sessionStandaloneText = typeof res.text === 'string' ? res.text : '';
964
+ } catch (e) {
965
+ if (requestSeq !== this.sessionStandaloneRequestSeq) {
966
+ return;
967
+ }
968
+ this.sessionStandaloneText = '';
969
+ this.sessionStandaloneError = '加载会话内容失败: ' + e.message;
970
+ } finally {
971
+ if (requestSeq === this.sessionStandaloneRequestSeq) {
972
+ this.sessionStandaloneLoading = false;
973
+ }
974
+ }
975
+ },
976
+
977
+ async loadActiveSessionDetail(options = {}) {
978
+ const result = await loadActiveSessionDetailHelper.call(this, api, options);
979
+ if (this.mainTab === 'sessions' && typeof this.scheduleSessionListMessageCountHydrate === 'function') {
980
+ this.scheduleSessionListMessageCountHydrate();
981
+ }
982
+ return result;
983
+ }
984
+ };
985
+ }