codexmate 0.0.29 → 0.0.30

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