codexmate 0.0.30 → 0.0.32

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 (144) hide show
  1. package/README.md +363 -421
  2. package/README.zh.md +371 -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 -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 +324 -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 -65
  16. package/cli/session-convert-io.js +82 -82
  17. package/cli/session-convert.js +150 -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 +15829 -15481
  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 +426 -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 +647 -645
  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 +781 -765
  60. package/web-ui/modules/api.mjs +90 -90
  61. package/web-ui/modules/app.computed.dashboard.mjs +248 -248
  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 +693 -999
  65. package/web-ui/modules/app.constants.mjs +15 -15
  66. package/web-ui/modules/app.methods.agents.mjs +651 -632
  67. package/web-ui/modules/app.methods.claude-config.mjs +200 -200
  68. package/web-ui/modules/app.methods.codex-config.mjs +861 -917
  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 -774
  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 -529
  76. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  77. package/web-ui/modules/app.methods.session-actions.mjs +591 -593
  78. package/web-ui/modules/app.methods.session-browser.mjs +1012 -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 +537 -534
  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 +3177 -3146
  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 -482
  95. package/web-ui/partials/index/layout-footer.html +13 -13
  96. package/web-ui/partials/index/layout-header.html +503 -500
  97. package/web-ui/partials/index/modal-config-template-agents.html +185 -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 +136 -194
  104. package/web-ui/partials/index/panel-config-codex.html +197 -337
  105. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  106. package/web-ui/partials/index/panel-dashboard.html +219 -219
  107. package/web-ui/partials/index/panel-docs.html +115 -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 +313 -308
  112. package/web-ui/partials/index/panel-settings.html +190 -190
  113. package/web-ui/partials/index/panel-trash.html +83 -88
  114. package/web-ui/partials/index/panel-usage.html +138 -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 +591 -594
  118. package/web-ui/source-bundle.cjs +233 -233
  119. package/web-ui/styles/base-theme.css +281 -281
  120. package/web-ui/styles/bridge-pool.css +197 -0
  121. package/web-ui/styles/controls-forms.css +433 -422
  122. package/web-ui/styles/dashboard.css +406 -406
  123. package/web-ui/styles/docs-panel.css +245 -271
  124. package/web-ui/styles/feedback.css +108 -108
  125. package/web-ui/styles/health-check-dialog.css +144 -144
  126. package/web-ui/styles/layout-shell.css +638 -626
  127. package/web-ui/styles/modals-core.css +466 -466
  128. package/web-ui/styles/navigation-panels.css +391 -391
  129. package/web-ui/styles/openclaw-structured.css +266 -266
  130. package/web-ui/styles/plugins-panel.css +564 -564
  131. package/web-ui/styles/responsive.css +392 -454
  132. package/web-ui/styles/sessions-list.css +647 -417
  133. package/web-ui/styles/sessions-preview.css +407 -407
  134. package/web-ui/styles/sessions-toolbar-trash.css +518 -334
  135. package/web-ui/styles/sessions-usage.css +588 -1040
  136. package/web-ui/styles/settings-panel.css +349 -349
  137. package/web-ui/styles/skills-list.css +305 -305
  138. package/web-ui/styles/skills-market.css +429 -429
  139. package/web-ui/styles/task-orchestration.css +822 -822
  140. package/web-ui/styles/titles-cards.css +472 -472
  141. package/web-ui/styles/trash-panel.css +90 -90
  142. package/web-ui/styles/webhook.css +81 -81
  143. package/web-ui/styles.css +24 -23
  144. package/web-ui.html +17 -17
@@ -1,984 +1,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
- 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
+ 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
+ }