codexmate 0.0.32 → 0.0.34

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 (148) hide show
  1. package/README.md +147 -363
  2. package/README.zh.md +147 -371
  3. package/cli/agents-files.js +230 -224
  4. package/cli/archive-helpers.js +453 -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 -402
  9. package/cli/config-health.js +454 -454
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/local-bridge.js +556 -324
  13. package/cli/openai-bridge.js +1653 -1653
  14. package/cli/openclaw-config.js +629 -629
  15. package/cli/session-convert-args.js +69 -69
  16. package/cli/session-convert-io.js +82 -82
  17. package/cli/session-convert.js +150 -150
  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/update.js +171 -0
  23. package/cli/zip-commands.js +510 -510
  24. package/cli.js +16079 -15829
  25. package/lib/automation.js +404 -404
  26. package/lib/cli-file-utils.js +151 -151
  27. package/lib/cli-models-utils.js +440 -440
  28. package/lib/cli-network-utils.js +190 -190
  29. package/lib/cli-path-utils.js +85 -85
  30. package/lib/cli-session-utils.js +121 -121
  31. package/lib/cli-sessions.js +427 -426
  32. package/lib/cli-utils.js +155 -155
  33. package/lib/cli-webhook.js +154 -126
  34. package/lib/download-artifacts.js +92 -92
  35. package/lib/mcp-stdio.js +453 -453
  36. package/lib/task-orchestrator.js +869 -869
  37. package/lib/text-diff.js +303 -303
  38. package/lib/win-tray.js +119 -0
  39. package/lib/workflow-engine.js +340 -340
  40. package/package.json +76 -76
  41. package/plugins/README.md +20 -20
  42. package/plugins/README.zh-CN.md +20 -20
  43. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  44. package/plugins/prompt-templates/computed.mjs +253 -253
  45. package/plugins/prompt-templates/index.mjs +8 -8
  46. package/plugins/prompt-templates/manifest.mjs +15 -15
  47. package/plugins/prompt-templates/methods.mjs +553 -553
  48. package/plugins/prompt-templates/overview.mjs +91 -91
  49. package/plugins/prompt-templates/ownership.mjs +19 -19
  50. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  51. package/plugins/prompt-templates/storage.mjs +64 -64
  52. package/plugins/registry.mjs +16 -16
  53. package/web-ui/app.js +654 -647
  54. package/web-ui/index.html +37 -36
  55. package/web-ui/logic.agents-diff.mjs +386 -386
  56. package/web-ui/logic.claude.mjs +172 -168
  57. package/web-ui/logic.codex.mjs +69 -69
  58. package/web-ui/logic.mjs +5 -5
  59. package/web-ui/logic.runtime.mjs +128 -128
  60. package/web-ui/logic.session-convert.mjs +70 -70
  61. package/web-ui/logic.sessions.mjs +781 -781
  62. package/web-ui/modules/api.mjs +90 -90
  63. package/web-ui/modules/app.computed.dashboard.mjs +248 -248
  64. package/web-ui/modules/app.computed.index.mjs +17 -17
  65. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  66. package/web-ui/modules/app.computed.session.mjs +735 -693
  67. package/web-ui/modules/app.constants.mjs +15 -15
  68. package/web-ui/modules/app.methods.agents.mjs +651 -651
  69. package/web-ui/modules/app.methods.claude-config.mjs +306 -200
  70. package/web-ui/modules/app.methods.codex-config.mjs +869 -861
  71. package/web-ui/modules/app.methods.index.mjs +94 -94
  72. package/web-ui/modules/app.methods.install.mjs +205 -205
  73. package/web-ui/modules/app.methods.navigation.mjs +788 -774
  74. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  75. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  76. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  77. package/web-ui/modules/app.methods.providers.mjs +575 -529
  78. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  79. package/web-ui/modules/app.methods.session-actions.mjs +591 -591
  80. package/web-ui/modules/app.methods.session-browser.mjs +1011 -1012
  81. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  82. package/web-ui/modules/app.methods.session-trash.mjs +438 -438
  83. package/web-ui/modules/app.methods.startup-claude.mjs +547 -537
  84. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  85. package/web-ui/modules/app.methods.webhook.mjs +87 -79
  86. package/web-ui/modules/config-mode.computed.mjs +124 -124
  87. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  88. package/web-ui/modules/i18n.dict.mjs +3195 -3177
  89. package/web-ui/modules/i18n.mjs +62 -62
  90. package/web-ui/modules/plugins.computed.mjs +3 -3
  91. package/web-ui/modules/plugins.methods.mjs +3 -3
  92. package/web-ui/modules/plugins.storage.mjs +11 -11
  93. package/web-ui/modules/provider-url-display.mjs +17 -17
  94. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  95. package/web-ui/modules/skills.computed.mjs +107 -107
  96. package/web-ui/modules/skills.methods.mjs +482 -482
  97. package/web-ui/partials/index/layout-footer.html +13 -13
  98. package/web-ui/partials/index/layout-header.html +499 -503
  99. package/web-ui/partials/index/modal-config-template-agents.html +185 -185
  100. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  101. package/web-ui/partials/index/modal-health-check.html +45 -45
  102. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  103. package/web-ui/partials/index/modal-skills.html +200 -200
  104. package/web-ui/partials/index/modal-webhook.html +42 -0
  105. package/web-ui/partials/index/modals-basic.html +223 -162
  106. package/web-ui/partials/index/panel-config-claude.html +155 -136
  107. package/web-ui/partials/index/panel-config-codex.html +176 -196
  108. package/web-ui/partials/index/panel-config-codex.html.bak +337 -0
  109. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  110. package/web-ui/partials/index/panel-dashboard.html +186 -219
  111. package/web-ui/partials/index/panel-docs.html +114 -114
  112. package/web-ui/partials/index/panel-market.html +177 -177
  113. package/web-ui/partials/index/panel-orchestration.html +391 -391
  114. package/web-ui/partials/index/panel-plugins.html +253 -253
  115. package/web-ui/partials/index/panel-sessions.html +319 -313
  116. package/web-ui/partials/index/panel-settings.html +158 -190
  117. package/web-ui/partials/index/panel-trash.html +82 -82
  118. package/web-ui/partials/index/panel-usage.html +137 -137
  119. package/web-ui/res/json5.min.js +1 -1
  120. package/web-ui/res/vue.global.prod.js +13 -13
  121. package/web-ui/session-helpers.mjs +591 -591
  122. package/web-ui/source-bundle.cjs +233 -233
  123. package/web-ui/styles/base-theme.css +281 -281
  124. package/web-ui/styles/bridge-pool.css +266 -197
  125. package/web-ui/styles/controls-forms.css +433 -433
  126. package/web-ui/styles/dashboard.css +406 -406
  127. package/web-ui/styles/docs-panel.css +245 -245
  128. package/web-ui/styles/feedback.css +108 -108
  129. package/web-ui/styles/health-check-dialog.css +144 -144
  130. package/web-ui/styles/layout-shell.css +628 -638
  131. package/web-ui/styles/modals-core.css +499 -466
  132. package/web-ui/styles/navigation-panels.css +391 -391
  133. package/web-ui/styles/openclaw-structured.css +266 -266
  134. package/web-ui/styles/plugins-panel.css +564 -564
  135. package/web-ui/styles/responsive.css +392 -392
  136. package/web-ui/styles/sessions-list.css +683 -647
  137. package/web-ui/styles/sessions-preview.css +407 -407
  138. package/web-ui/styles/sessions-toolbar-trash.css +518 -518
  139. package/web-ui/styles/sessions-usage.css +588 -588
  140. package/web-ui/styles/settings-panel.css +415 -349
  141. package/web-ui/styles/skills-list.css +305 -305
  142. package/web-ui/styles/skills-market.css +429 -429
  143. package/web-ui/styles/task-orchestration.css +822 -822
  144. package/web-ui/styles/titles-cards.css +472 -472
  145. package/web-ui/styles/trash-panel.css +90 -90
  146. package/web-ui/styles/webhook.css +115 -81
  147. package/web-ui/styles.css +24 -24
  148. package/web-ui.html +17 -17
@@ -1,1012 +1,1011 @@
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
- setSessionSource(value) {
470
- if (this.sessionsLoading) return;
471
- this.sessionFilterSource = value;
472
- this.refreshSessionPathOptions(value);
473
- this.persistSessionFilterCache();
474
- syncSessionsFilterUrl(this);
475
- this.loadSessions();
476
- },
477
-
478
- highlightQueryText(text) {
479
- if (typeof text !== 'string' || !text) return text;
480
- var tokens = this.queryTokens;
481
- if (!tokens || tokens.length === 0) return text;
482
- var result = text;
483
- for (var i = 0; i < tokens.length; i++) {
484
- var token = tokens[i];
485
- var escaped = token.replace(/[.*+?^${}()|[\]\\]/g, '\\ async onSessionSourceChange(event) {');
486
- var re = new RegExp('(' + escaped + ')', 'gi');
487
- result = result.replace(re, '<mark>$1</mark>');
488
- }
489
- return result;
490
- },
491
-
492
- async onSessionSourceChange(event) {
493
- const rawValue = event && event.target && typeof event.target.value === 'string'
494
- ? event.target.value
495
- : this.sessionFilterSource;
496
- const cached = buildSessionFilterCacheState(rawValue, this.sessionPathFilter);
497
- this.sessionFilterSource = cached.source;
498
- this.refreshSessionPathOptions(this.sessionFilterSource);
499
- this.persistSessionFilterCache();
500
- syncSessionsFilterUrl(this);
501
- await this.loadSessions();
502
- },
503
-
504
- async onSessionPathFilterChange() {
505
- this.persistSessionFilterCache();
506
- syncSessionsFilterUrl(this);
507
- await this.loadSessions();
508
- },
509
-
510
- async onSessionFilterChange() {
511
- this.persistSessionFilterCache();
512
- syncSessionsFilterUrl(this);
513
- await this.loadSessions();
514
- },
515
-
516
- hasActiveSessionFilters() {
517
- if (this.sessionFilterSource && this.sessionFilterSource !== 'all') return true;
518
- if (this.sessionPathFilter) return true;
519
- if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) return true;
520
- if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') return true;
521
- if (this.sessionTimePreset && this.sessionTimePreset !== 'all') return true;
522
- return false;
523
- },
524
-
525
- getSessionFilterChips() {
526
- const chips = [];
527
- if (this.sessionFilterSource && this.sessionFilterSource !== 'all') {
528
- const label = this.sessionFilterSource === 'codex'
529
- ? this.t('sessions.source.codex')
530
- : (this.sessionFilterSource === 'claude'
531
- ? this.t('sessions.source.claudeCode')
532
- : (this.sessionFilterSource === 'gemini'
533
- ? this.t('sessions.source.gemini')
534
- : (this.sessionFilterSource === 'codebuddy' ? this.t('sessions.source.codebuddy') : this.sessionFilterSource)));
535
- chips.push({ key: 'source', title: this.t('sessions.filters.source'), value: label });
536
- }
537
- if (this.sessionPathFilter) {
538
- chips.push({ key: 'path', title: this.t('sessions.filters.path'), value: this.sessionPathFilter });
539
- }
540
- if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
541
- chips.push({ key: 'query', title: this.t('sessions.filters.keyword'), value: this.sessionQuery });
542
- }
543
- if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') {
544
- const label = this.sessionRoleFilter === 'user'
545
- ? this.t('sessions.role.user')
546
- : (this.sessionRoleFilter === 'assistant'
547
- ? this.t('sessions.role.assistant')
548
- : (this.sessionRoleFilter === 'system' ? this.t('sessions.role.system') : this.sessionRoleFilter));
549
- chips.push({ key: 'role', title: this.t('sessions.filters.role'), value: label });
550
- }
551
- if (this.sessionTimePreset && this.sessionTimePreset !== 'all') {
552
- const label = this.sessionTimePreset === '7d'
553
- ? this.t('sessions.time.7d')
554
- : (this.sessionTimePreset === '30d'
555
- ? this.t('sessions.time.30d')
556
- : (this.sessionTimePreset === '90d' ? this.t('sessions.time.90d') : this.sessionTimePreset));
557
- chips.push({ key: 'time', title: this.t('sessions.filters.time'), value: label });
558
- }
559
- return chips;
560
- },
561
-
562
- async clearSessionFilterChip(key) {
563
- const normalized = typeof key === 'string' ? key.trim().toLowerCase() : '';
564
- if (normalized === 'source') this.sessionFilterSource = 'all';
565
- if (normalized === 'path') this.sessionPathFilter = '';
566
- if (normalized === 'query') this.sessionQuery = '';
567
- if (normalized === 'role') this.sessionRoleFilter = 'all';
568
- if (normalized === 'time') this.sessionTimePreset = 'all';
569
- this.persistSessionFilterCache();
570
- syncSessionsFilterUrl(this);
571
- await this.loadSessions();
572
- },
573
-
574
- async clearSessionFilters() {
575
- this.sessionFilterSource = 'all';
576
- this.sessionPathFilter = '';
577
- this.sessionQuery = '';
578
- this.sessionRoleFilter = 'all';
579
- this.sessionTimePreset = 'all';
580
- this.persistSessionFilterCache();
581
- syncSessionsFilterUrl(this);
582
- await this.onSessionSourceChange();
583
- },
584
-
585
- async copySessionsFilterShareUrl() {
586
- const url = buildSessionsFilterShareUrl(this);
587
- if (!url) {
588
- this.showMessage(typeof this.t === 'function' ? this.t('sessions.filters.urlBuildFail') : 'Failed to build link', 'error');
589
- return;
590
- }
591
- try {
592
- if (navigator.clipboard && window.isSecureContext) {
593
- await navigator.clipboard.writeText(url);
594
- this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.ok') : 'Copied', 'success');
595
- return;
596
- }
597
- } catch (_) {}
598
- const ok = typeof this.fallbackCopyText === 'function' ? this.fallbackCopyText(url) : false;
599
- if (ok) {
600
- this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.ok') : 'Copied', 'success');
601
- return;
602
- }
603
- this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.fail') : 'Copy failed', 'error');
604
- },
605
-
606
- normalizeSessionMessage(message) {
607
- const fallback = {
608
- role: 'assistant',
609
- normalizedRole: 'assistant',
610
- roleLabel: 'Assistant',
611
- text: typeof message === 'string' ? message : '',
612
- timestamp: ''
613
- };
614
- const safeMessage = message && typeof message === 'object' ? message : fallback;
615
- const normalizedRole = normalizeSessionMessageRole(
616
- safeMessage.normalizedRole || safeMessage.role
617
- );
618
- const roleLabel = normalizedRole === 'user'
619
- ? 'User'
620
- : (normalizedRole === 'system' ? 'System' : 'Assistant');
621
- return {
622
- ...safeMessage,
623
- role: normalizedRole,
624
- normalizedRole,
625
- roleLabel
626
- };
627
- },
628
-
629
- getRecordKey(message) {
630
- if (!message || !Number.isInteger(message.recordLineIndex) || message.recordLineIndex < 0) {
631
- return '';
632
- }
633
- return String(message.recordLineIndex);
634
- },
635
-
636
- getRecordRenderKey(message, idx) {
637
- const recordKey = this.getRecordKey(message);
638
- if (recordKey) {
639
- return `record-${recordKey}`;
640
- }
641
- return `record-fallback-${idx}-${message && message.timestamp ? message.timestamp : ''}`;
642
- },
643
-
644
- syncActiveSessionMessageCount(messageCount) {
645
- if (!Number.isFinite(messageCount) || messageCount < 0) return;
646
- if (this.activeSession) {
647
- this.activeSession.messageCount = messageCount;
648
- }
649
- const activeKey = this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
650
- if (!activeKey) return;
651
- const matched = this.sessionsList.find(item => this.getSessionExportKey(item) === activeKey);
652
- if (matched) {
653
- matched.messageCount = messageCount;
654
- }
655
- },
656
-
657
- cancelScheduledSessionListMessageCountHydrate() {
658
- const handle = this.__sessionListMessageCountHydrateHandle || null;
659
- if (!handle) return;
660
- if (typeof this.cancelIdleTask === 'function') {
661
- this.cancelIdleTask(handle);
662
- }
663
- this.__sessionListMessageCountHydrateHandle = null;
664
- },
665
-
666
- resetSessionListMessageCountHydrate() {
667
- this.cancelScheduledSessionListMessageCountHydrate();
668
- this.__sessionListMessageCountHydrateInFlight = false;
669
- this.__sessionListMessageCountHydrateLastScheduleAt = 0;
670
- this.__sessionListMessageCountHydrateLastAttemptAtMap = {};
671
- this.sessionListMessageCountHydrateRequestSeq = (Number(this.sessionListMessageCountHydrateRequestSeq) || 0) + 1;
672
- },
673
-
674
- scheduleSessionListMessageCountHydrate() {
675
- if (this.mainTab !== 'sessions' || !this.sessionListRenderEnabled) {
676
- return;
677
- }
678
- const now = Date.now();
679
- const lastAt = Number(this.__sessionListMessageCountHydrateLastScheduleAt || 0);
680
- if ((now - lastAt) < 120) {
681
- return;
682
- }
683
- this.__sessionListMessageCountHydrateLastScheduleAt = now;
684
- this.cancelScheduledSessionListMessageCountHydrate();
685
- const run = () => {
686
- this.__sessionListMessageCountHydrateHandle = null;
687
- void this.hydrateVisibleSessionListMessageCounts();
688
- };
689
- if (typeof this.scheduleIdleTask === 'function') {
690
- this.__sessionListMessageCountHydrateHandle = this.scheduleIdleTask(run, 160);
691
- return;
692
- }
693
- if (typeof this.scheduleAfterFrame === 'function') {
694
- this.scheduleAfterFrame(run);
695
- return;
696
- }
697
- run();
698
- },
699
-
700
- async hydrateVisibleSessionListMessageCounts() {
701
- if (this.__sessionListMessageCountHydrateInFlight) {
702
- return;
703
- }
704
- if (this.mainTab !== 'sessions' || !this.sessionListRenderEnabled) {
705
- return;
706
- }
707
-
708
- const visible = Array.isArray(this.visibleSessionsList) ? this.visibleSessionsList : [];
709
- if (!visible.length) return;
710
-
711
- const now = Date.now();
712
- const lastAttemptAtMap = (this.__sessionListMessageCountHydrateLastAttemptAtMap && typeof this.__sessionListMessageCountHydrateLastAttemptAtMap === 'object')
713
- ? this.__sessionListMessageCountHydrateLastAttemptAtMap
714
- : {};
715
- const targets = [];
716
- for (const session of visible) {
717
- if (!session || typeof session !== 'object') continue;
718
- const messageCountRaw = Number(session.messageCount);
719
- const shouldHydrate = !Number.isFinite(messageCountRaw) || (messageCountRaw === 0 && !session.__messageCountExact);
720
- if (!shouldHydrate) continue;
721
- const key = this.getSessionExportKey(session);
722
- if (!key) continue;
723
- const lastAttempt = Number(lastAttemptAtMap[key] || 0);
724
- if ((now - lastAttempt) < 5000) {
725
- continue;
726
- }
727
- lastAttemptAtMap[key] = now;
728
- targets.push({
729
- source: session.source,
730
- sessionId: session.sessionId,
731
- filePath: session.filePath
732
- });
733
- if (targets.length >= 32) {
734
- break;
735
- }
736
- }
737
- this.__sessionListMessageCountHydrateLastAttemptAtMap = lastAttemptAtMap;
738
- if (!targets.length) return;
739
-
740
- const requestSeq = (Number(this.sessionListMessageCountHydrateRequestSeq) || 0) + 1;
741
- this.sessionListMessageCountHydrateRequestSeq = requestSeq;
742
- this.__sessionListMessageCountHydrateInFlight = true;
743
- try {
744
- const res = await api('session-message-counts', {
745
- items: targets,
746
- limit: targets.length
747
- });
748
- if (requestSeq !== Number(this.sessionListMessageCountHydrateRequestSeq || 0)) {
749
- return;
750
- }
751
- if (!res || res.error || !Array.isArray(res.items)) {
752
- return;
753
- }
754
- const byKey = new Map();
755
- for (const item of res.items) {
756
- if (!item || typeof item !== 'object') continue;
757
- const key = typeof item.key === 'string' ? item.key : '';
758
- if (!key) continue;
759
- const messageCount = Number(item.messageCount);
760
- if (!Number.isFinite(messageCount) || messageCount < 0) continue;
761
- byKey.set(key, Math.floor(messageCount));
762
- }
763
- if (!byKey.size) {
764
- return;
765
- }
766
- const sessions = Array.isArray(this.sessionsList) ? this.sessionsList : [];
767
- const sessionMap = new Map(sessions.map((session) => [this.getSessionExportKey(session), session]));
768
- for (const [key, count] of byKey.entries()) {
769
- const matched = sessionMap.get(key);
770
- if (matched) {
771
- matched.messageCount = count;
772
- }
773
- if (this.activeSession && this.getSessionExportKey(this.activeSession) === key) {
774
- this.activeSession.messageCount = count;
775
- }
776
- }
777
- } catch (_) {
778
- return;
779
- } finally {
780
- if (requestSeq === Number(this.sessionListMessageCountHydrateRequestSeq || 0)) {
781
- this.__sessionListMessageCountHydrateInFlight = false;
782
- }
783
- }
784
- },
785
-
786
- invalidateSessionsUsageData(options = {}) {
787
- this.sessionsUsageLoadedOnce = false;
788
- this.sessionsUsageLoadedLimit = 0;
789
- this.sessionsUsageError = '';
790
- if (options.preserveList !== true) {
791
- this.sessionsUsageList = [];
792
- }
793
- },
794
-
795
- setSessionsUsageTimeRange(nextRange) {
796
- const normalized = typeof nextRange === 'string' ? nextRange.trim().toLowerCase() : '';
797
- const range = normalized === 'all' ? 'all' : (normalized === '30d' ? '30d' : '7d');
798
- this.sessionsUsageTimeRange = range;
799
- try { localStorage.setItem('sessionsUsageTimeRange', range); } catch (_) {}
800
- if (range === 'all') {
801
- this.sessionsUsageCompareEnabled = false;
802
- }
803
- void this.loadSessionsUsage({ range });
804
- },
805
-
806
- toggleSessionsUsageCompare() {
807
- if (this.sessionsUsageTimeRange === 'all') {
808
- this.sessionsUsageCompareEnabled = false;
809
- return;
810
- }
811
- this.sessionsUsageCompareEnabled = !this.sessionsUsageCompareEnabled;
812
- const range = typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '7d';
813
- void this.loadSessionsUsage({
814
- range,
815
- limit: this.sessionsUsageCompareEnabled ? 2000 : undefined
816
- });
817
- },
818
-
819
- selectSessionsUsageDay(dayKey) {
820
- const normalized = typeof dayKey === 'string' ? dayKey.trim() : '';
821
- this.sessionsUsageSelectedDayKey = normalized;
822
- },
823
-
824
- clearSessionsUsageDay() {
825
- this.sessionsUsageSelectedDayKey = '';
826
- },
827
-
828
- async loadSessionsUsage(options = {}) {
829
- if (this.sessionsUsageLoading) return;
830
- const normalizedRange = typeof options.range === 'string'
831
- ? options.range.trim().toLowerCase()
832
- : (typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '');
833
- const range = normalizedRange === 'all' ? 'all' : (normalizedRange === '30d' ? '30d' : '7d');
834
- const defaultLimit = range === 'all' ? 2000 : (range === '30d' ? 1200 : 600);
835
- const rawLimit = Number(options.limit);
836
- const compareBoost = this.sessionsUsageCompareEnabled && range !== 'all'
837
- ? 2000
838
- : defaultLimit;
839
- const limit = Number.isFinite(rawLimit)
840
- ? Math.max(1, Math.min(rawLimit, 2000))
841
- : compareBoost;
842
- const loadedLimit = Number(this.sessionsUsageLoadedLimit || 0);
843
- const lastRange = typeof this.sessionsUsageLastLoadedRange === 'string'
844
- ? this.sessionsUsageLastLoadedRange
845
- : '';
846
- const rangeChanged = lastRange && lastRange !== range;
847
- if (this.sessionsUsageLoadedOnce && !options.forceRefresh && !rangeChanged && loadedLimit >= limit) {
848
- return;
849
- }
850
- this.sessionsUsageLoading = true;
851
- this.sessionsUsageError = '';
852
- let loadSucceeded = false;
853
- try {
854
- const res = await api('list-sessions-usage', {
855
- source: 'all',
856
- limit,
857
- forceRefresh: !!options.forceRefresh
858
- });
859
- if (res.error) {
860
- this.sessionsUsageError = res.error;
861
- this.showMessage(res.error, 'error');
862
- return;
863
- }
864
- this.sessionsUsageList = Array.isArray(res.sessions) ? res.sessions : [];
865
- loadSucceeded = true;
866
- } catch (e) {
867
- this.sessionsUsageError = '加载 usage 统计失败';
868
- this.showMessage('加载 usage 统计失败', 'error');
869
- } finally {
870
- this.sessionsUsageLoading = false;
871
- if (loadSucceeded) {
872
- this.sessionsUsageLoadedOnce = true;
873
- this.sessionsUsageLoadedLimit = limit;
874
- this.sessionsUsageLastLoadedRange = range;
875
- if (!this.sessionsUsageSelectedDayKey && Array.isArray(this.sessionUsageDailyTableRows) && this.sessionUsageDailyTableRows.length > 0) {
876
- this.sessionsUsageSelectedDayKey = this.sessionUsageDailyTableRows[0].key;
877
- }
878
- }
879
- }
880
- },
881
-
882
- async loadSessions(options = {}) {
883
- this.resetSessionListMessageCountHydrate();
884
- const result = await loadSessionsHelper.call(this, api, options || {});
885
- this.pruneSessionPinnedMap(this.sessionsList);
886
- return result;
887
- },
888
-
889
- async selectSession(session) {
890
- if (!session) {
891
- emitSessionLoadNativeDialog(this, 'selectSession:skip-empty');
892
- return;
893
- }
894
- emitSessionLoadNativeDialog(
895
- this,
896
- 'selectSession:start',
897
- `sessionId=${session.sessionId || ''}\nsource=${session.source || ''}`
898
- );
899
- const isSameSession = this.activeSession
900
- && this.getSessionExportKey(this.activeSession) === this.getSessionExportKey(session);
901
- if (isSameSession) {
902
- emitSessionLoadNativeDialog(this, 'selectSession:same-session', `sessionId=${session.sessionId || ''}`);
903
- if (this.sessionDetailLoading) {
904
- emitSessionLoadNativeDialog(this, 'selectSession:skip-detail-loading', `sessionId=${session.sessionId || ''}`);
905
- return;
906
- }
907
- const currentMessages = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages : [];
908
- if (currentMessages.length > 0) {
909
- emitSessionLoadNativeDialog(
910
- this,
911
- 'selectSession:skip-existing-messages',
912
- `sessionId=${session.sessionId || ''}\nmessages=${currentMessages.length}`
913
- );
914
- return;
915
- }
916
- if (typeof this.scheduleAfterFrame === 'function') {
917
- const selectedSession = this.activeSession;
918
- emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
919
- this.scheduleAfterFrame(() => {
920
- if (this.activeSession !== selectedSession) return;
921
- void this.loadActiveSessionDetail();
922
- });
923
- return;
924
- }
925
- emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
926
- await this.loadActiveSessionDetail();
927
- return;
928
- }
929
- this.activeSession = session;
930
- emitSessionLoadNativeDialog(this, 'selectSession:activate', `sessionId=${session.sessionId || ''}`);
931
- if (typeof this.expandVisibleSessionList === 'function') {
932
- this.expandVisibleSessionList(0, { ensureActive: true });
933
- }
934
- this.activeSessionMessages = [];
935
- this.resetSessionDetailPagination();
936
- this.resetSessionPreviewMessageRender();
937
- this.activeSessionDetailError = '';
938
- this.activeSessionDetailClipped = false;
939
- this.cancelSessionTimelineSync();
940
- this.sessionTimelineActiveKey = '';
941
- this.clearSessionTimelineRefs();
942
- if (typeof this.scheduleAfterFrame === 'function') {
943
- const selectedSession = this.activeSession;
944
- emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
945
- this.scheduleAfterFrame(() => {
946
- if (this.activeSession !== selectedSession) return;
947
- void this.loadActiveSessionDetail();
948
- });
949
- return;
950
- }
951
- emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
952
- await this.loadActiveSessionDetail();
953
- },
954
-
955
- async loadSessionStandalonePlain() {
956
- if (!this.activeSession) {
957
- this.sessionStandaloneRequestSeq += 1;
958
- this.sessionStandaloneLoading = false;
959
- this.sessionStandaloneText = '';
960
- this.sessionStandaloneTitle = '会话';
961
- this.sessionStandaloneSourceLabel = '';
962
- this.sessionStandaloneError = '';
963
- return;
964
- }
965
-
966
- const requestSeq = ++this.sessionStandaloneRequestSeq;
967
- const sessionSnapshot = this.activeSession;
968
- this.sessionStandaloneLoading = true;
969
- this.sessionStandaloneError = '';
970
- try {
971
- const res = await api('session-plain', {
972
- source: sessionSnapshot.source,
973
- sessionId: sessionSnapshot.sessionId,
974
- filePath: sessionSnapshot.filePath,
975
- maxMessages: sessionSnapshot.maxMessages || 50
976
- });
977
-
978
- if (requestSeq !== this.sessionStandaloneRequestSeq) {
979
- return;
980
- }
981
-
982
- if (res.error) {
983
- this.sessionStandaloneText = '';
984
- this.sessionStandaloneError = res.error;
985
- return;
986
- }
987
-
988
- this.sessionStandaloneSourceLabel = res.sourceLabel || sessionSnapshot.sourceLabel || '';
989
- this.sessionStandaloneTitle = res.sessionId || sessionSnapshot.title || '会话';
990
- this.sessionStandaloneText = typeof res.text === 'string' ? res.text : '';
991
- } catch (e) {
992
- if (requestSeq !== this.sessionStandaloneRequestSeq) {
993
- return;
994
- }
995
- this.sessionStandaloneText = '';
996
- this.sessionStandaloneError = '加载会话内容失败: ' + e.message;
997
- } finally {
998
- if (requestSeq === this.sessionStandaloneRequestSeq) {
999
- this.sessionStandaloneLoading = false;
1000
- }
1001
- }
1002
- },
1003
-
1004
- async loadActiveSessionDetail(options = {}) {
1005
- const result = await loadActiveSessionDetailHelper.call(this, api, options);
1006
- if (this.mainTab === 'sessions' && typeof this.scheduleSessionListMessageCountHydrate === 'function') {
1007
- this.scheduleSessionListMessageCountHydrate();
1008
- }
1009
- return result;
1010
- }
1011
- };
1012
- }
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
+ setSessionSource(value) {
470
+ if (this.sessionsLoading) return;
471
+ this.sessionFilterSource = value;
472
+ this.refreshSessionPathOptions(value);
473
+ this.persistSessionFilterCache();
474
+ syncSessionsFilterUrl(this);
475
+ this.loadSessions();
476
+ },
477
+
478
+ highlightQueryText(text) {
479
+ if (typeof text !== 'string' || !text) return text;
480
+ var tokens = this.queryTokens;
481
+ if (!tokens || tokens.length === 0) return text;
482
+ var escaped = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
483
+ for (var i = 0; i < tokens.length; i++) {
484
+ var token = tokens[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
485
+ var re = new RegExp('(' + token + ')', 'gi');
486
+ escaped = escaped.replace(re, '<mark>$1</mark>');
487
+ }
488
+ return escaped;
489
+ },
490
+
491
+ async onSessionSourceChange(event) {
492
+ const rawValue = event && event.target && typeof event.target.value === 'string'
493
+ ? event.target.value
494
+ : this.sessionFilterSource;
495
+ const cached = buildSessionFilterCacheState(rawValue, this.sessionPathFilter);
496
+ this.sessionFilterSource = cached.source;
497
+ this.refreshSessionPathOptions(this.sessionFilterSource);
498
+ this.persistSessionFilterCache();
499
+ syncSessionsFilterUrl(this);
500
+ await this.loadSessions();
501
+ },
502
+
503
+ async onSessionPathFilterChange() {
504
+ this.persistSessionFilterCache();
505
+ syncSessionsFilterUrl(this);
506
+ await this.loadSessions();
507
+ },
508
+
509
+ async onSessionFilterChange() {
510
+ this.persistSessionFilterCache();
511
+ syncSessionsFilterUrl(this);
512
+ await this.loadSessions();
513
+ },
514
+
515
+ hasActiveSessionFilters() {
516
+ if (this.sessionFilterSource && this.sessionFilterSource !== 'all') return true;
517
+ if (this.sessionPathFilter) return true;
518
+ if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) return true;
519
+ if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') return true;
520
+ if (this.sessionTimePreset && this.sessionTimePreset !== 'all') return true;
521
+ return false;
522
+ },
523
+
524
+ getSessionFilterChips() {
525
+ const chips = [];
526
+ if (this.sessionFilterSource && this.sessionFilterSource !== 'all') {
527
+ const label = this.sessionFilterSource === 'codex'
528
+ ? this.t('sessions.source.codex')
529
+ : (this.sessionFilterSource === 'claude'
530
+ ? this.t('sessions.source.claudeCode')
531
+ : (this.sessionFilterSource === 'gemini'
532
+ ? this.t('sessions.source.gemini')
533
+ : (this.sessionFilterSource === 'codebuddy' ? this.t('sessions.source.codebuddy') : this.sessionFilterSource)));
534
+ chips.push({ key: 'source', title: this.t('sessions.filters.source'), value: label });
535
+ }
536
+ if (this.sessionPathFilter) {
537
+ chips.push({ key: 'path', title: this.t('sessions.filters.path'), value: this.sessionPathFilter });
538
+ }
539
+ if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
540
+ chips.push({ key: 'query', title: this.t('sessions.filters.keyword'), value: this.sessionQuery });
541
+ }
542
+ if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') {
543
+ const label = this.sessionRoleFilter === 'user'
544
+ ? this.t('sessions.role.user')
545
+ : (this.sessionRoleFilter === 'assistant'
546
+ ? this.t('sessions.role.assistant')
547
+ : (this.sessionRoleFilter === 'system' ? this.t('sessions.role.system') : this.sessionRoleFilter));
548
+ chips.push({ key: 'role', title: this.t('sessions.filters.role'), value: label });
549
+ }
550
+ if (this.sessionTimePreset && this.sessionTimePreset !== 'all') {
551
+ const label = this.sessionTimePreset === '7d'
552
+ ? this.t('sessions.time.7d')
553
+ : (this.sessionTimePreset === '30d'
554
+ ? this.t('sessions.time.30d')
555
+ : (this.sessionTimePreset === '90d' ? this.t('sessions.time.90d') : this.sessionTimePreset));
556
+ chips.push({ key: 'time', title: this.t('sessions.filters.time'), value: label });
557
+ }
558
+ return chips;
559
+ },
560
+
561
+ async clearSessionFilterChip(key) {
562
+ const normalized = typeof key === 'string' ? key.trim().toLowerCase() : '';
563
+ if (normalized === 'source') this.sessionFilterSource = 'all';
564
+ if (normalized === 'path') this.sessionPathFilter = '';
565
+ if (normalized === 'query') this.sessionQuery = '';
566
+ if (normalized === 'role') this.sessionRoleFilter = 'all';
567
+ if (normalized === 'time') this.sessionTimePreset = 'all';
568
+ this.persistSessionFilterCache();
569
+ syncSessionsFilterUrl(this);
570
+ await this.loadSessions();
571
+ },
572
+
573
+ async clearSessionFilters() {
574
+ this.sessionFilterSource = 'all';
575
+ this.sessionPathFilter = '';
576
+ this.sessionQuery = '';
577
+ this.sessionRoleFilter = 'all';
578
+ this.sessionTimePreset = 'all';
579
+ this.persistSessionFilterCache();
580
+ syncSessionsFilterUrl(this);
581
+ await this.onSessionSourceChange();
582
+ },
583
+
584
+ async copySessionsFilterShareUrl() {
585
+ const url = buildSessionsFilterShareUrl(this);
586
+ if (!url) {
587
+ this.showMessage(typeof this.t === 'function' ? this.t('sessions.filters.urlBuildFail') : 'Failed to build link', 'error');
588
+ return;
589
+ }
590
+ try {
591
+ if (navigator.clipboard && window.isSecureContext) {
592
+ await navigator.clipboard.writeText(url);
593
+ this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.ok') : 'Copied', 'success');
594
+ return;
595
+ }
596
+ } catch (_) {}
597
+ const ok = typeof this.fallbackCopyText === 'function' ? this.fallbackCopyText(url) : false;
598
+ if (ok) {
599
+ this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.ok') : 'Copied', 'success');
600
+ return;
601
+ }
602
+ this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.fail') : 'Copy failed', 'error');
603
+ },
604
+
605
+ normalizeSessionMessage(message) {
606
+ const fallback = {
607
+ role: 'assistant',
608
+ normalizedRole: 'assistant',
609
+ roleLabel: 'Assistant',
610
+ text: typeof message === 'string' ? message : '',
611
+ timestamp: ''
612
+ };
613
+ const safeMessage = message && typeof message === 'object' ? message : fallback;
614
+ const normalizedRole = normalizeSessionMessageRole(
615
+ safeMessage.normalizedRole || safeMessage.role
616
+ );
617
+ const roleLabel = normalizedRole === 'user'
618
+ ? 'User'
619
+ : (normalizedRole === 'system' ? 'System' : 'Assistant');
620
+ return {
621
+ ...safeMessage,
622
+ role: normalizedRole,
623
+ normalizedRole,
624
+ roleLabel
625
+ };
626
+ },
627
+
628
+ getRecordKey(message) {
629
+ if (!message || !Number.isInteger(message.recordLineIndex) || message.recordLineIndex < 0) {
630
+ return '';
631
+ }
632
+ return String(message.recordLineIndex);
633
+ },
634
+
635
+ getRecordRenderKey(message, idx) {
636
+ const recordKey = this.getRecordKey(message);
637
+ if (recordKey) {
638
+ return `record-${recordKey}`;
639
+ }
640
+ return `record-fallback-${idx}-${message && message.timestamp ? message.timestamp : ''}`;
641
+ },
642
+
643
+ syncActiveSessionMessageCount(messageCount) {
644
+ if (!Number.isFinite(messageCount) || messageCount < 0) return;
645
+ if (this.activeSession) {
646
+ this.activeSession.messageCount = messageCount;
647
+ }
648
+ const activeKey = this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
649
+ if (!activeKey) return;
650
+ const matched = this.sessionsList.find(item => this.getSessionExportKey(item) === activeKey);
651
+ if (matched) {
652
+ matched.messageCount = messageCount;
653
+ }
654
+ },
655
+
656
+ cancelScheduledSessionListMessageCountHydrate() {
657
+ const handle = this.__sessionListMessageCountHydrateHandle || null;
658
+ if (!handle) return;
659
+ if (typeof this.cancelIdleTask === 'function') {
660
+ this.cancelIdleTask(handle);
661
+ }
662
+ this.__sessionListMessageCountHydrateHandle = null;
663
+ },
664
+
665
+ resetSessionListMessageCountHydrate() {
666
+ this.cancelScheduledSessionListMessageCountHydrate();
667
+ this.__sessionListMessageCountHydrateInFlight = false;
668
+ this.__sessionListMessageCountHydrateLastScheduleAt = 0;
669
+ this.__sessionListMessageCountHydrateLastAttemptAtMap = {};
670
+ this.sessionListMessageCountHydrateRequestSeq = (Number(this.sessionListMessageCountHydrateRequestSeq) || 0) + 1;
671
+ },
672
+
673
+ scheduleSessionListMessageCountHydrate() {
674
+ if (this.mainTab !== 'sessions' || !this.sessionListRenderEnabled) {
675
+ return;
676
+ }
677
+ const now = Date.now();
678
+ const lastAt = Number(this.__sessionListMessageCountHydrateLastScheduleAt || 0);
679
+ if ((now - lastAt) < 120) {
680
+ return;
681
+ }
682
+ this.__sessionListMessageCountHydrateLastScheduleAt = now;
683
+ this.cancelScheduledSessionListMessageCountHydrate();
684
+ const run = () => {
685
+ this.__sessionListMessageCountHydrateHandle = null;
686
+ void this.hydrateVisibleSessionListMessageCounts();
687
+ };
688
+ if (typeof this.scheduleIdleTask === 'function') {
689
+ this.__sessionListMessageCountHydrateHandle = this.scheduleIdleTask(run, 160);
690
+ return;
691
+ }
692
+ if (typeof this.scheduleAfterFrame === 'function') {
693
+ this.scheduleAfterFrame(run);
694
+ return;
695
+ }
696
+ run();
697
+ },
698
+
699
+ async hydrateVisibleSessionListMessageCounts() {
700
+ if (this.__sessionListMessageCountHydrateInFlight) {
701
+ return;
702
+ }
703
+ if (this.mainTab !== 'sessions' || !this.sessionListRenderEnabled) {
704
+ return;
705
+ }
706
+
707
+ const visible = Array.isArray(this.visibleSessionsList) ? this.visibleSessionsList : [];
708
+ if (!visible.length) return;
709
+
710
+ const now = Date.now();
711
+ const lastAttemptAtMap = (this.__sessionListMessageCountHydrateLastAttemptAtMap && typeof this.__sessionListMessageCountHydrateLastAttemptAtMap === 'object')
712
+ ? this.__sessionListMessageCountHydrateLastAttemptAtMap
713
+ : {};
714
+ const targets = [];
715
+ for (const session of visible) {
716
+ if (!session || typeof session !== 'object') continue;
717
+ const messageCountRaw = Number(session.messageCount);
718
+ const shouldHydrate = !Number.isFinite(messageCountRaw) || (messageCountRaw === 0 && !session.__messageCountExact);
719
+ if (!shouldHydrate) continue;
720
+ const key = this.getSessionExportKey(session);
721
+ if (!key) continue;
722
+ const lastAttempt = Number(lastAttemptAtMap[key] || 0);
723
+ if ((now - lastAttempt) < 5000) {
724
+ continue;
725
+ }
726
+ lastAttemptAtMap[key] = now;
727
+ targets.push({
728
+ source: session.source,
729
+ sessionId: session.sessionId,
730
+ filePath: session.filePath
731
+ });
732
+ if (targets.length >= 32) {
733
+ break;
734
+ }
735
+ }
736
+ this.__sessionListMessageCountHydrateLastAttemptAtMap = lastAttemptAtMap;
737
+ if (!targets.length) return;
738
+
739
+ const requestSeq = (Number(this.sessionListMessageCountHydrateRequestSeq) || 0) + 1;
740
+ this.sessionListMessageCountHydrateRequestSeq = requestSeq;
741
+ this.__sessionListMessageCountHydrateInFlight = true;
742
+ try {
743
+ const res = await api('session-message-counts', {
744
+ items: targets,
745
+ limit: targets.length
746
+ });
747
+ if (requestSeq !== Number(this.sessionListMessageCountHydrateRequestSeq || 0)) {
748
+ return;
749
+ }
750
+ if (!res || res.error || !Array.isArray(res.items)) {
751
+ return;
752
+ }
753
+ const byKey = new Map();
754
+ for (const item of res.items) {
755
+ if (!item || typeof item !== 'object') continue;
756
+ const key = typeof item.key === 'string' ? item.key : '';
757
+ if (!key) continue;
758
+ const messageCount = Number(item.messageCount);
759
+ if (!Number.isFinite(messageCount) || messageCount < 0) continue;
760
+ byKey.set(key, Math.floor(messageCount));
761
+ }
762
+ if (!byKey.size) {
763
+ return;
764
+ }
765
+ const sessions = Array.isArray(this.sessionsList) ? this.sessionsList : [];
766
+ const sessionMap = new Map(sessions.map((session) => [this.getSessionExportKey(session), session]));
767
+ for (const [key, count] of byKey.entries()) {
768
+ const matched = sessionMap.get(key);
769
+ if (matched) {
770
+ matched.messageCount = count;
771
+ }
772
+ if (this.activeSession && this.getSessionExportKey(this.activeSession) === key) {
773
+ this.activeSession.messageCount = count;
774
+ }
775
+ }
776
+ } catch (_) {
777
+ return;
778
+ } finally {
779
+ if (requestSeq === Number(this.sessionListMessageCountHydrateRequestSeq || 0)) {
780
+ this.__sessionListMessageCountHydrateInFlight = false;
781
+ }
782
+ }
783
+ },
784
+
785
+ invalidateSessionsUsageData(options = {}) {
786
+ this.sessionsUsageLoadedOnce = false;
787
+ this.sessionsUsageLoadedLimit = 0;
788
+ this.sessionsUsageError = '';
789
+ if (options.preserveList !== true) {
790
+ this.sessionsUsageList = [];
791
+ }
792
+ },
793
+
794
+ setSessionsUsageTimeRange(nextRange) {
795
+ const normalized = typeof nextRange === 'string' ? nextRange.trim().toLowerCase() : '';
796
+ const range = normalized === 'all' ? 'all' : (normalized === '30d' ? '30d' : '7d');
797
+ this.sessionsUsageTimeRange = range;
798
+ try { localStorage.setItem('sessionsUsageTimeRange', range); } catch (_) {}
799
+ if (range === 'all') {
800
+ this.sessionsUsageCompareEnabled = false;
801
+ }
802
+ void this.loadSessionsUsage({ range });
803
+ },
804
+
805
+ toggleSessionsUsageCompare() {
806
+ if (this.sessionsUsageTimeRange === 'all') {
807
+ this.sessionsUsageCompareEnabled = false;
808
+ return;
809
+ }
810
+ this.sessionsUsageCompareEnabled = !this.sessionsUsageCompareEnabled;
811
+ const range = typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '7d';
812
+ void this.loadSessionsUsage({
813
+ range,
814
+ limit: this.sessionsUsageCompareEnabled ? 2000 : undefined
815
+ });
816
+ },
817
+
818
+ selectSessionsUsageDay(dayKey) {
819
+ const normalized = typeof dayKey === 'string' ? dayKey.trim() : '';
820
+ this.sessionsUsageSelectedDayKey = normalized;
821
+ },
822
+
823
+ clearSessionsUsageDay() {
824
+ this.sessionsUsageSelectedDayKey = '';
825
+ },
826
+
827
+ async loadSessionsUsage(options = {}) {
828
+ if (this.sessionsUsageLoading) return;
829
+ const normalizedRange = typeof options.range === 'string'
830
+ ? options.range.trim().toLowerCase()
831
+ : (typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '');
832
+ const range = normalizedRange === 'all' ? 'all' : (normalizedRange === '30d' ? '30d' : '7d');
833
+ const defaultLimit = range === 'all' ? 2000 : (range === '30d' ? 1200 : 600);
834
+ const rawLimit = Number(options.limit);
835
+ const compareBoost = this.sessionsUsageCompareEnabled && range !== 'all'
836
+ ? 2000
837
+ : defaultLimit;
838
+ const limit = Number.isFinite(rawLimit)
839
+ ? Math.max(1, Math.min(rawLimit, 2000))
840
+ : compareBoost;
841
+ const loadedLimit = Number(this.sessionsUsageLoadedLimit || 0);
842
+ const lastRange = typeof this.sessionsUsageLastLoadedRange === 'string'
843
+ ? this.sessionsUsageLastLoadedRange
844
+ : '';
845
+ const rangeChanged = lastRange && lastRange !== range;
846
+ if (this.sessionsUsageLoadedOnce && !options.forceRefresh && !rangeChanged && loadedLimit >= limit) {
847
+ return;
848
+ }
849
+ this.sessionsUsageLoading = true;
850
+ this.sessionsUsageError = '';
851
+ let loadSucceeded = false;
852
+ try {
853
+ const res = await api('list-sessions-usage', {
854
+ source: 'all',
855
+ limit,
856
+ forceRefresh: !!options.forceRefresh
857
+ });
858
+ if (res.error) {
859
+ this.sessionsUsageError = res.error;
860
+ this.showMessage(res.error, 'error');
861
+ return;
862
+ }
863
+ this.sessionsUsageList = Array.isArray(res.sessions) ? res.sessions : [];
864
+ loadSucceeded = true;
865
+ } catch (e) {
866
+ this.sessionsUsageError = '加载 usage 统计失败';
867
+ this.showMessage('加载 usage 统计失败', 'error');
868
+ } finally {
869
+ this.sessionsUsageLoading = false;
870
+ if (loadSucceeded) {
871
+ this.sessionsUsageLoadedOnce = true;
872
+ this.sessionsUsageLoadedLimit = limit;
873
+ this.sessionsUsageLastLoadedRange = range;
874
+ if (!this.sessionsUsageSelectedDayKey && Array.isArray(this.sessionUsageDailyTableRows) && this.sessionUsageDailyTableRows.length > 0) {
875
+ this.sessionsUsageSelectedDayKey = this.sessionUsageDailyTableRows[0].key;
876
+ }
877
+ }
878
+ }
879
+ },
880
+
881
+ async loadSessions(options = {}) {
882
+ this.resetSessionListMessageCountHydrate();
883
+ const result = await loadSessionsHelper.call(this, api, options || {});
884
+ this.pruneSessionPinnedMap(this.sessionsList);
885
+ return result;
886
+ },
887
+
888
+ async selectSession(session) {
889
+ if (!session) {
890
+ emitSessionLoadNativeDialog(this, 'selectSession:skip-empty');
891
+ return;
892
+ }
893
+ emitSessionLoadNativeDialog(
894
+ this,
895
+ 'selectSession:start',
896
+ `sessionId=${session.sessionId || ''}\nsource=${session.source || ''}`
897
+ );
898
+ const isSameSession = this.activeSession
899
+ && this.getSessionExportKey(this.activeSession) === this.getSessionExportKey(session);
900
+ if (isSameSession) {
901
+ emitSessionLoadNativeDialog(this, 'selectSession:same-session', `sessionId=${session.sessionId || ''}`);
902
+ if (this.sessionDetailLoading) {
903
+ emitSessionLoadNativeDialog(this, 'selectSession:skip-detail-loading', `sessionId=${session.sessionId || ''}`);
904
+ return;
905
+ }
906
+ const currentMessages = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages : [];
907
+ if (currentMessages.length > 0) {
908
+ emitSessionLoadNativeDialog(
909
+ this,
910
+ 'selectSession:skip-existing-messages',
911
+ `sessionId=${session.sessionId || ''}\nmessages=${currentMessages.length}`
912
+ );
913
+ return;
914
+ }
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
+ return;
927
+ }
928
+ this.activeSession = session;
929
+ emitSessionLoadNativeDialog(this, 'selectSession:activate', `sessionId=${session.sessionId || ''}`);
930
+ if (typeof this.expandVisibleSessionList === 'function') {
931
+ this.expandVisibleSessionList(0, { ensureActive: true });
932
+ }
933
+ this.activeSessionMessages = [];
934
+ this.resetSessionDetailPagination();
935
+ this.resetSessionPreviewMessageRender();
936
+ this.activeSessionDetailError = '';
937
+ this.activeSessionDetailClipped = false;
938
+ this.cancelSessionTimelineSync();
939
+ this.sessionTimelineActiveKey = '';
940
+ this.clearSessionTimelineRefs();
941
+ if (typeof this.scheduleAfterFrame === 'function') {
942
+ const selectedSession = this.activeSession;
943
+ emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
944
+ this.scheduleAfterFrame(() => {
945
+ if (this.activeSession !== selectedSession) return;
946
+ void this.loadActiveSessionDetail();
947
+ });
948
+ return;
949
+ }
950
+ emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
951
+ await this.loadActiveSessionDetail();
952
+ },
953
+
954
+ async loadSessionStandalonePlain() {
955
+ if (!this.activeSession) {
956
+ this.sessionStandaloneRequestSeq += 1;
957
+ this.sessionStandaloneLoading = false;
958
+ this.sessionStandaloneText = '';
959
+ this.sessionStandaloneTitle = '会话';
960
+ this.sessionStandaloneSourceLabel = '';
961
+ this.sessionStandaloneError = '';
962
+ return;
963
+ }
964
+
965
+ const requestSeq = ++this.sessionStandaloneRequestSeq;
966
+ const sessionSnapshot = this.activeSession;
967
+ this.sessionStandaloneLoading = true;
968
+ this.sessionStandaloneError = '';
969
+ try {
970
+ const res = await api('session-plain', {
971
+ source: sessionSnapshot.source,
972
+ sessionId: sessionSnapshot.sessionId,
973
+ filePath: sessionSnapshot.filePath,
974
+ maxMessages: sessionSnapshot.maxMessages || 50
975
+ });
976
+
977
+ if (requestSeq !== this.sessionStandaloneRequestSeq) {
978
+ return;
979
+ }
980
+
981
+ if (res.error) {
982
+ this.sessionStandaloneText = '';
983
+ this.sessionStandaloneError = res.error;
984
+ return;
985
+ }
986
+
987
+ this.sessionStandaloneSourceLabel = res.sourceLabel || sessionSnapshot.sourceLabel || '';
988
+ this.sessionStandaloneTitle = res.sessionId || sessionSnapshot.title || '会话';
989
+ this.sessionStandaloneText = typeof res.text === 'string' ? res.text : '';
990
+ } catch (e) {
991
+ if (requestSeq !== this.sessionStandaloneRequestSeq) {
992
+ return;
993
+ }
994
+ this.sessionStandaloneText = '';
995
+ this.sessionStandaloneError = '加载会话内容失败: ' + e.message;
996
+ } finally {
997
+ if (requestSeq === this.sessionStandaloneRequestSeq) {
998
+ this.sessionStandaloneLoading = false;
999
+ }
1000
+ }
1001
+ },
1002
+
1003
+ async loadActiveSessionDetail(options = {}) {
1004
+ const result = await loadActiveSessionDetailHelper.call(this, api, options);
1005
+ if (this.mainTab === 'sessions' && typeof this.scheduleSessionListMessageCountHydrate === 'function') {
1006
+ this.scheduleSessionListMessageCountHydrate();
1007
+ }
1008
+ return result;
1009
+ }
1010
+ };
1011
+ }