codexmate 0.0.21 → 0.0.23

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 (115) hide show
  1. package/README.md +390 -284
  2. package/README.zh.md +322 -0
  3. package/cli/agents-files.js +224 -162
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +359 -359
  6. package/cli/builtin-proxy.js +1044 -580
  7. package/cli/claude-proxy.js +998 -998
  8. package/cli/config-bootstrap.js +384 -384
  9. package/cli/config-health.js +338 -338
  10. package/cli/openai-bridge.js +950 -0
  11. package/cli/openclaw-config.js +629 -629
  12. package/cli/session-usage.concurrent.js +28 -0
  13. package/cli/session-usage.js +112 -0
  14. package/cli/session-usage.models.js +176 -0
  15. package/cli/skills.js +1141 -1141
  16. package/cli/zip-commands.js +510 -510
  17. package/cli.js +13214 -13129
  18. package/lib/cli-file-utils.js +151 -151
  19. package/lib/cli-models-utils.js +419 -419
  20. package/lib/cli-network-utils.js +164 -164
  21. package/lib/cli-path-utils.js +69 -69
  22. package/lib/cli-session-utils.js +121 -121
  23. package/lib/cli-sessions.js +386 -386
  24. package/lib/cli-utils.js +155 -155
  25. package/lib/download-artifacts.js +77 -77
  26. package/lib/mcp-stdio.js +440 -440
  27. package/lib/task-orchestrator.js +869 -869
  28. package/lib/text-diff.js +303 -303
  29. package/lib/workflow-engine.js +340 -340
  30. package/package.json +74 -74
  31. package/res/json5.min.js +1 -1
  32. package/res/logo.png +0 -0
  33. package/res/vue.global.prod.js +13 -13
  34. package/web-ui/app.js +626 -530
  35. package/web-ui/index.html +34 -33
  36. package/web-ui/logic.agents-diff.mjs +386 -386
  37. package/web-ui/logic.claude.mjs +168 -168
  38. package/web-ui/logic.mjs +5 -5
  39. package/web-ui/logic.runtime.mjs +128 -124
  40. package/web-ui/logic.sessions.mjs +614 -581
  41. package/web-ui/modules/api.mjs +90 -90
  42. package/web-ui/modules/app.computed.dashboard.mjs +126 -113
  43. package/web-ui/modules/app.computed.index.mjs +17 -15
  44. package/web-ui/modules/app.computed.main-tabs.mjs +202 -195
  45. package/web-ui/modules/app.computed.session.mjs +653 -507
  46. package/web-ui/modules/app.constants.mjs +15 -15
  47. package/web-ui/modules/app.methods.agents.mjs +544 -493
  48. package/web-ui/modules/app.methods.claude-config.mjs +174 -174
  49. package/web-ui/modules/app.methods.codex-config.mjs +795 -640
  50. package/web-ui/modules/app.methods.index.mjs +92 -88
  51. package/web-ui/modules/app.methods.install.mjs +177 -149
  52. package/web-ui/modules/app.methods.navigation.mjs +662 -619
  53. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  54. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  55. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  56. package/web-ui/modules/app.methods.providers.mjs +404 -363
  57. package/web-ui/modules/app.methods.runtime.mjs +323 -323
  58. package/web-ui/modules/app.methods.session-actions.mjs +537 -520
  59. package/web-ui/modules/app.methods.session-browser.mjs +691 -626
  60. package/web-ui/modules/app.methods.session-timeline.mjs +448 -448
  61. package/web-ui/modules/app.methods.session-trash.mjs +422 -422
  62. package/web-ui/modules/app.methods.startup-claude.mjs +417 -412
  63. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -471
  64. package/web-ui/modules/config-mode.computed.mjs +126 -126
  65. package/web-ui/modules/config-template-confirm-pref.mjs +33 -0
  66. package/web-ui/modules/i18n.mjs +1823 -0
  67. package/web-ui/modules/plugins.computed.mjs +3 -0
  68. package/web-ui/modules/plugins.methods.mjs +3 -0
  69. package/web-ui/modules/plugins.storage.mjs +11 -0
  70. package/web-ui/modules/sessions-filters-url.mjs +85 -0
  71. package/web-ui/modules/skills.computed.mjs +107 -107
  72. package/web-ui/modules/skills.methods.mjs +481 -481
  73. package/web-ui/partials/index/layout-footer.html +13 -13
  74. package/web-ui/partials/index/layout-header.html +461 -402
  75. package/web-ui/partials/index/modal-config-template-agents.html +175 -125
  76. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  77. package/web-ui/partials/index/modal-health-check.html +72 -72
  78. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  79. package/web-ui/partials/index/modal-skills.html +200 -184
  80. package/web-ui/partials/index/modals-basic.html +165 -156
  81. package/web-ui/partials/index/panel-config-claude.html +159 -126
  82. package/web-ui/partials/index/panel-config-codex.html +255 -237
  83. package/web-ui/partials/index/panel-config-openclaw.html +78 -78
  84. package/web-ui/partials/index/panel-docs.html +147 -130
  85. package/web-ui/partials/index/panel-market.html +174 -174
  86. package/web-ui/partials/index/panel-orchestration.html +388 -397
  87. package/web-ui/partials/index/panel-plugins.html +273 -0
  88. package/web-ui/partials/index/panel-sessions.html +298 -292
  89. package/web-ui/partials/index/panel-settings.html +258 -190
  90. package/web-ui/partials/index/panel-usage.html +353 -213
  91. package/web-ui/session-helpers.mjs +573 -559
  92. package/web-ui/source-bundle.cjs +233 -233
  93. package/web-ui/styles/base-theme.css +264 -271
  94. package/web-ui/styles/controls-forms.css +369 -360
  95. package/web-ui/styles/docs-panel.css +247 -182
  96. package/web-ui/styles/feedback.css +108 -108
  97. package/web-ui/styles/health-check-dialog.css +144 -144
  98. package/web-ui/styles/layout-shell.css +602 -376
  99. package/web-ui/styles/modals-core.css +464 -464
  100. package/web-ui/styles/navigation-panels.css +390 -348
  101. package/web-ui/styles/openclaw-structured.css +266 -266
  102. package/web-ui/styles/plugins-panel.css +523 -0
  103. package/web-ui/styles/responsive.css +456 -450
  104. package/web-ui/styles/sessions-list.css +400 -400
  105. package/web-ui/styles/sessions-preview.css +411 -411
  106. package/web-ui/styles/sessions-toolbar-trash.css +268 -243
  107. package/web-ui/styles/sessions-usage.css +879 -628
  108. package/web-ui/styles/settings-panel.css +166 -0
  109. package/web-ui/styles/skills-list.css +303 -296
  110. package/web-ui/styles/skills-market.css +406 -335
  111. package/web-ui/styles/task-orchestration.css +822 -776
  112. package/web-ui/styles/titles-cards.css +408 -408
  113. package/web-ui/styles.css +20 -18
  114. package/web-ui.html +17 -17
  115. package/README.en.md +0 -349
@@ -1,626 +1,691 @@
1
- import {
2
- buildSessionFilterCacheState,
3
- isSessionQueryEnabled,
4
- normalizeSessionMessageRole,
5
- normalizeSessionPathFilter
6
- } from '../logic.mjs';
7
-
8
- function isSessionLoadNativeDialogEnabled(vm) {
9
- if (vm && typeof vm.isSessionLoadNativeDialogEnabled === 'function' && vm.isSessionLoadNativeDialogEnabled !== isSessionLoadNativeDialogEnabled) {
10
- try {
11
- return !!vm.isSessionLoadNativeDialogEnabled();
12
- } catch (_) {
13
- // fall through to shared detection
14
- }
15
- }
16
-
17
- try {
18
- if (globalThis && globalThis.__CODEXMATE_SESSION_LOAD_NATIVE_DIALOG__ === true) {
19
- return true;
20
- }
21
- } catch (_) {
22
- // ignore global flag lookup failures
23
- }
24
-
25
- try {
26
- if (typeof localStorage !== 'undefined' && typeof localStorage.getItem === 'function') {
27
- const stored = String(localStorage.getItem('codexmateSessionLoadNativeDialog') || '').trim().toLowerCase();
28
- if (stored === '1' || stored === 'true' || stored === 'yes' || stored === 'on') {
29
- return true;
30
- }
31
- }
32
- } catch (_) {
33
- // ignore storage lookup failures
34
- }
35
-
36
- try {
37
- const search = typeof location !== 'undefined' && location && typeof location.search === 'string'
38
- ? location.search
39
- : (typeof window !== 'undefined' && window.location && typeof window.location.search === 'string'
40
- ? window.location.search
41
- : '');
42
- if (!search) {
43
- return false;
44
- }
45
- const params = new URLSearchParams(search);
46
- const value = String(params.get('sessionLoadNativeDialog') || '').trim().toLowerCase();
47
- return value === '1' || value === 'true' || value === 'yes' || value === 'on';
48
- } catch (_) {
49
- return false;
50
- }
51
- }
52
-
53
- function emitSessionLoadNativeDialog(vm, step, details = '') {
54
- if (!isSessionLoadNativeDialogEnabled(vm)) {
55
- return;
56
- }
57
- const alertFn = typeof globalThis.alert === 'function'
58
- ? globalThis.alert.bind(globalThis)
59
- : (typeof window !== 'undefined' && typeof window.alert === 'function'
60
- ? window.alert.bind(window)
61
- : null);
62
- if (!alertFn) {
63
- return;
64
- }
65
- const message = details
66
- ? `[codexmate][session-load] ${step}\n${details}`
67
- : `[codexmate][session-load] ${step}`;
68
- alertFn(message);
69
- }
70
-
71
- export function createSessionBrowserMethods(options = {}) {
72
- const {
73
- api,
74
- loadSessionsHelper,
75
- loadActiveSessionDetailHelper
76
- } = options;
77
-
78
- return {
79
- normalizeSessionPathValue(value) {
80
- return normalizeSessionPathFilter(value);
81
- },
82
-
83
- mergeSessionPathOptions(baseList = [], incomingList = []) {
84
- const merged = [];
85
- const seen = new Set();
86
- const append = (items) => {
87
- if (!Array.isArray(items)) return;
88
- for (const item of items) {
89
- const value = this.normalizeSessionPathValue(item);
90
- if (!value) continue;
91
- const key = value.toLowerCase();
92
- if (seen.has(key)) continue;
93
- seen.add(key);
94
- merged.push(value);
95
- }
96
- };
97
-
98
- append(baseList);
99
- append(incomingList);
100
- return merged;
101
- },
102
-
103
- extractPathOptionsFromSessions(sessions) {
104
- const paths = [];
105
- if (!Array.isArray(sessions)) {
106
- return paths;
107
- }
108
-
109
- const seen = new Set();
110
- for (const session of sessions) {
111
- const value = this.normalizeSessionPathValue(session && session.cwd ? session.cwd : '');
112
- if (!value) continue;
113
- const key = value.toLowerCase();
114
- if (seen.has(key)) continue;
115
- seen.add(key);
116
- paths.push(value);
117
- }
118
- return paths;
119
- },
120
-
121
- syncSessionPathOptionsForSource(source, nextOptions, mergeWithExisting = false) {
122
- const targetSource = source === 'claude' ? 'claude' : (source === 'all' ? 'all' : 'codex');
123
- const current = Array.isArray(this.sessionPathOptionsMap[targetSource])
124
- ? this.sessionPathOptionsMap[targetSource]
125
- : [];
126
- const merged = mergeWithExisting
127
- ? this.mergeSessionPathOptions(current, nextOptions)
128
- : this.mergeSessionPathOptions([], nextOptions);
129
- this.sessionPathOptionsMap = {
130
- ...this.sessionPathOptionsMap,
131
- [targetSource]: merged
132
- };
133
- this.refreshSessionPathOptions(targetSource);
134
- },
135
-
136
- refreshSessionPathOptions(source) {
137
- const targetSource = source === 'claude' ? 'claude' : (source === 'all' ? 'all' : 'codex');
138
- const base = Array.isArray(this.sessionPathOptionsMap[targetSource])
139
- ? [...this.sessionPathOptionsMap[targetSource]]
140
- : [];
141
- const selected = this.normalizeSessionPathValue(this.sessionPathFilter);
142
- if (selected && !base.some(item => item.toLowerCase() === selected.toLowerCase())) {
143
- base.unshift(selected);
144
- }
145
- if (targetSource === this.sessionFilterSource) {
146
- this.sessionPathOptions = base;
147
- }
148
- },
149
-
150
- isSessionLoadNativeDialogEnabled() {
151
- return isSessionLoadNativeDialogEnabled(this);
152
- },
153
-
154
- emitSessionLoadNativeDialog(step, details = '') {
155
- emitSessionLoadNativeDialog(this, step, details);
156
- },
157
-
158
- async loadSessionPathOptions(options = {}) {
159
- const source = options.source === 'claude' ? 'claude' : (options.source === 'all' ? 'all' : 'codex');
160
- const forceRefresh = !!options.forceRefresh;
161
- const loaded = !!this.sessionPathOptionsLoadedMap[source];
162
- if (!forceRefresh && loaded) {
163
- emitSessionLoadNativeDialog(this, 'loadSessionPathOptions:cache-hit', `source=${source}`);
164
- if (source === this.sessionFilterSource) {
165
- this.sessionPathOptionsLoading = false;
166
- }
167
- return;
168
- }
169
-
170
- const nextSeqMap = {
171
- ...(this.sessionPathRequestSeqMap || {})
172
- };
173
- const requestSeq = (Number(nextSeqMap[source]) || 0) + 1;
174
- nextSeqMap[source] = requestSeq;
175
- this.sessionPathRequestSeqMap = nextSeqMap;
176
- emitSessionLoadNativeDialog(
177
- this,
178
- 'loadSessionPathOptions:start',
179
- `source=${source}\nforceRefresh=${forceRefresh}\nrequestSeq=${requestSeq}`
180
- );
181
- if (source === this.sessionFilterSource) {
182
- this.sessionPathOptionsLoading = true;
183
- }
184
- try {
185
- const res = await api('list-session-paths', {
186
- source,
187
- limit: 500,
188
- forceRefresh
189
- });
190
- if (requestSeq !== Number(((this.sessionPathRequestSeqMap || {})[source]) || 0)) {
191
- emitSessionLoadNativeDialog(
192
- this,
193
- 'loadSessionPathOptions:stale-response',
194
- `source=${source}\nrequestSeq=${requestSeq}`
195
- );
196
- return;
197
- }
198
- if (res && !res.error && Array.isArray(res.paths)) {
199
- this.syncSessionPathOptionsForSource(source, res.paths, true);
200
- this.sessionPathOptionsLoadedMap = {
201
- ...this.sessionPathOptionsLoadedMap,
202
- [source]: true
203
- };
204
- emitSessionLoadNativeDialog(
205
- this,
206
- 'loadSessionPathOptions:success',
207
- `source=${source}\npaths=${res.paths.length}`
208
- );
209
- } else if (res && res.error) {
210
- emitSessionLoadNativeDialog(
211
- this,
212
- 'loadSessionPathOptions:error',
213
- `source=${source}\nerror=${res.error}`
214
- );
215
- }
216
- } catch (error) {
217
- emitSessionLoadNativeDialog(
218
- this,
219
- 'loadSessionPathOptions:exception',
220
- `source=${source}\nerror=${error && error.message ? error.message : String(error)}`
221
- );
222
- // 路径补全失败不影响会话主流程
223
- } finally {
224
- if (
225
- source === this.sessionFilterSource
226
- && requestSeq === Number(((this.sessionPathRequestSeqMap || {})[source]) || 0)
227
- ) {
228
- this.sessionPathOptionsLoading = false;
229
- }
230
- emitSessionLoadNativeDialog(
231
- this,
232
- 'loadSessionPathOptions:complete',
233
- `source=${source}\nrequestSeq=${requestSeq}`
234
- );
235
- }
236
- },
237
-
238
- onSessionResumeYoloChange() {
239
- const value = this.sessionResumeWithYolo ? '1' : '0';
240
- localStorage.setItem('codexmateSessionResumeYolo', value);
241
- },
242
-
243
- restoreSessionFilterCache() {
244
- const sourceCache = localStorage.getItem('codexmateSessionFilterSource');
245
- const pathCache = localStorage.getItem('codexmateSessionPathFilter');
246
- const cached = buildSessionFilterCacheState(sourceCache, pathCache);
247
- this.sessionFilterSource = cached.source;
248
- this.sessionPathFilter = cached.pathFilter;
249
- this.refreshSessionPathOptions(this.sessionFilterSource);
250
- },
251
-
252
- persistSessionFilterCache() {
253
- const cached = buildSessionFilterCacheState(this.sessionFilterSource, this.sessionPathFilter);
254
- localStorage.setItem('codexmateSessionFilterSource', cached.source);
255
- if (cached.pathFilter) {
256
- localStorage.setItem('codexmateSessionPathFilter', cached.pathFilter);
257
- } else {
258
- localStorage.removeItem('codexmateSessionPathFilter');
259
- }
260
- },
261
-
262
- normalizeSessionPinnedMap(raw) {
263
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
264
- return {};
265
- }
266
- const next = {};
267
- for (const [key, value] of Object.entries(raw)) {
268
- if (!key) continue;
269
- const numeric = Number(value);
270
- if (!Number.isFinite(numeric) || numeric <= 0) continue;
271
- next[key] = Math.floor(numeric);
272
- }
273
- return next;
274
- },
275
-
276
- restoreSessionPinnedMap() {
277
- const cached = localStorage.getItem('codexmateSessionPinnedMap');
278
- if (!cached) {
279
- this.sessionPinnedMap = {};
280
- return;
281
- }
282
- try {
283
- const parsed = JSON.parse(cached);
284
- this.sessionPinnedMap = this.normalizeSessionPinnedMap(parsed);
285
- } catch (_) {
286
- this.sessionPinnedMap = {};
287
- localStorage.removeItem('codexmateSessionPinnedMap');
288
- }
289
- },
290
-
291
- persistSessionPinnedMap() {
292
- const payload = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
293
- ? this.sessionPinnedMap
294
- : {};
295
- localStorage.setItem('codexmateSessionPinnedMap', JSON.stringify(payload));
296
- },
297
-
298
- shouldPruneSessionPinnedMap(sessions = this.sessionsList) {
299
- if (!Array.isArray(sessions) || sessions.length === 0) {
300
- return false;
301
- }
302
- if (this.sessionFilterSource !== 'all') {
303
- return false;
304
- }
305
- if (this.sessionPathFilter) {
306
- return false;
307
- }
308
- if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
309
- return false;
310
- }
311
- if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') {
312
- return false;
313
- }
314
- if (this.sessionTimePreset && this.sessionTimePreset !== 'all') {
315
- return false;
316
- }
317
- return true;
318
- },
319
-
320
- pruneSessionPinnedMap(sessions = this.sessionsList) {
321
- const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
322
- ? this.sessionPinnedMap
323
- : {};
324
- const list = Array.isArray(sessions) ? sessions : [];
325
- if (Object.keys(current).length === 0 || !this.shouldPruneSessionPinnedMap(list)) {
326
- return;
327
- }
328
- const validKeys = new Set(list.map((session) => this.getSessionExportKey(session)).filter(Boolean));
329
- const next = {};
330
- let changed = false;
331
- for (const [key, value] of Object.entries(current)) {
332
- if (!validKeys.has(key)) {
333
- changed = true;
334
- continue;
335
- }
336
- next[key] = value;
337
- }
338
- if (!changed) {
339
- return;
340
- }
341
- this.sessionPinnedMap = next;
342
- this.persistSessionPinnedMap();
343
- },
344
-
345
- getSessionPinTimestamp(session) {
346
- if (!session) return 0;
347
- const key = this.getSessionExportKey(session);
348
- if (!key) return 0;
349
- const raw = this.sessionPinnedMap && this.sessionPinnedMap[key];
350
- const numeric = Number(raw);
351
- return Number.isFinite(numeric) && numeric > 0 ? Math.floor(numeric) : 0;
352
- },
353
-
354
- isSessionPinned(session) {
355
- return this.getSessionPinTimestamp(session) > 0;
356
- },
357
-
358
- toggleSessionPin(session) {
359
- if (!session) return;
360
- const key = this.getSessionExportKey(session);
361
- if (!key) return;
362
- const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
363
- ? this.sessionPinnedMap
364
- : {};
365
- const next = { ...current };
366
- if (next[key]) {
367
- delete next[key];
368
- } else {
369
- next[key] = Date.now();
370
- }
371
- this.sessionPinnedMap = next;
372
- this.persistSessionPinnedMap();
373
- },
374
-
375
- removeSessionPin(session) {
376
- if (!session) return;
377
- const key = this.getSessionExportKey(session);
378
- if (!key) return;
379
- const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
380
- ? this.sessionPinnedMap
381
- : {};
382
- if (!current[key]) return;
383
- const next = { ...current };
384
- delete next[key];
385
- this.sessionPinnedMap = next;
386
- this.persistSessionPinnedMap();
387
- },
388
-
389
- async onSessionSourceChange() {
390
- this.refreshSessionPathOptions(this.sessionFilterSource);
391
- this.persistSessionFilterCache();
392
- await this.loadSessions();
393
- },
394
-
395
- async onSessionPathFilterChange() {
396
- this.persistSessionFilterCache();
397
- await this.loadSessions();
398
- },
399
-
400
- async onSessionFilterChange() {
401
- await this.loadSessions();
402
- },
403
-
404
- async clearSessionFilters() {
405
- this.sessionFilterSource = 'all';
406
- this.sessionPathFilter = '';
407
- this.sessionQuery = '';
408
- this.sessionRoleFilter = 'all';
409
- this.sessionTimePreset = 'all';
410
- this.persistSessionFilterCache();
411
- await this.onSessionSourceChange();
412
- },
413
-
414
- normalizeSessionMessage(message) {
415
- const fallback = {
416
- role: 'assistant',
417
- normalizedRole: 'assistant',
418
- roleLabel: 'Assistant',
419
- text: typeof message === 'string' ? message : '',
420
- timestamp: ''
421
- };
422
- const safeMessage = message && typeof message === 'object' ? message : fallback;
423
- const normalizedRole = normalizeSessionMessageRole(
424
- safeMessage.normalizedRole || safeMessage.role
425
- );
426
- const roleLabel = normalizedRole === 'user'
427
- ? 'User'
428
- : (normalizedRole === 'system' ? 'System' : 'Assistant');
429
- return {
430
- ...safeMessage,
431
- role: normalizedRole,
432
- normalizedRole,
433
- roleLabel
434
- };
435
- },
436
-
437
- getRecordKey(message) {
438
- if (!message || !Number.isInteger(message.recordLineIndex) || message.recordLineIndex < 0) {
439
- return '';
440
- }
441
- return String(message.recordLineIndex);
442
- },
443
-
444
- getRecordRenderKey(message, idx) {
445
- const recordKey = this.getRecordKey(message);
446
- if (recordKey) {
447
- return `record-${recordKey}`;
448
- }
449
- return `record-fallback-${idx}-${message && message.timestamp ? message.timestamp : ''}`;
450
- },
451
-
452
- syncActiveSessionMessageCount(messageCount) {
453
- if (!Number.isFinite(messageCount) || messageCount < 0) return;
454
- if (this.activeSession) {
455
- this.activeSession.messageCount = messageCount;
456
- }
457
- const activeKey = this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
458
- if (!activeKey) return;
459
- const matched = this.sessionsList.find(item => this.getSessionExportKey(item) === activeKey);
460
- if (matched) {
461
- matched.messageCount = messageCount;
462
- }
463
- },
464
-
465
- invalidateSessionsUsageData(options = {}) {
466
- this.sessionsUsageLoadedOnce = false;
467
- this.sessionsUsageError = '';
468
- if (options.preserveList !== true) {
469
- this.sessionsUsageList = [];
470
- }
471
- },
472
-
473
- async loadSessionsUsage(options = {}) {
474
- if (this.sessionsUsageLoading) return;
475
- this.sessionsUsageLoading = true;
476
- this.sessionsUsageError = '';
477
- let loadSucceeded = false;
478
- try {
479
- const res = await api('list-sessions-usage', {
480
- source: 'all',
481
- limit: 2000,
482
- forceRefresh: !!options.forceRefresh
483
- });
484
- if (res.error) {
485
- this.sessionsUsageError = res.error;
486
- this.showMessage(res.error, 'error');
487
- return;
488
- }
489
- this.sessionsUsageList = Array.isArray(res.sessions) ? res.sessions : [];
490
- loadSucceeded = true;
491
- } catch (e) {
492
- this.sessionsUsageError = '加载 usage 统计失败';
493
- this.showMessage('加载 usage 统计失败', 'error');
494
- } finally {
495
- this.sessionsUsageLoading = false;
496
- if (loadSucceeded) {
497
- this.sessionsUsageLoadedOnce = true;
498
- }
499
- }
500
- },
501
-
502
- async loadSessions(options = {}) {
503
- const result = await loadSessionsHelper.call(this, api, options || {});
504
- this.pruneSessionPinnedMap(this.sessionsList);
505
- return result;
506
- },
507
-
508
- async selectSession(session) {
509
- if (!session) {
510
- emitSessionLoadNativeDialog(this, 'selectSession:skip-empty');
511
- return;
512
- }
513
- emitSessionLoadNativeDialog(
514
- this,
515
- 'selectSession:start',
516
- `sessionId=${session.sessionId || ''}\nsource=${session.source || ''}`
517
- );
518
- const isSameSession = this.activeSession
519
- && this.getSessionExportKey(this.activeSession) === this.getSessionExportKey(session);
520
- if (isSameSession) {
521
- emitSessionLoadNativeDialog(this, 'selectSession:same-session', `sessionId=${session.sessionId || ''}`);
522
- if (this.sessionDetailLoading) {
523
- emitSessionLoadNativeDialog(this, 'selectSession:skip-detail-loading', `sessionId=${session.sessionId || ''}`);
524
- return;
525
- }
526
- const currentMessages = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages : [];
527
- if (currentMessages.length > 0) {
528
- emitSessionLoadNativeDialog(
529
- this,
530
- 'selectSession:skip-existing-messages',
531
- `sessionId=${session.sessionId || ''}\nmessages=${currentMessages.length}`
532
- );
533
- return;
534
- }
535
- if (typeof this.scheduleAfterFrame === 'function') {
536
- const selectedSession = this.activeSession;
537
- emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
538
- this.scheduleAfterFrame(() => {
539
- if (this.activeSession !== selectedSession) return;
540
- void this.loadActiveSessionDetail();
541
- });
542
- return;
543
- }
544
- emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
545
- await this.loadActiveSessionDetail();
546
- return;
547
- }
548
- this.activeSession = session;
549
- emitSessionLoadNativeDialog(this, 'selectSession:activate', `sessionId=${session.sessionId || ''}`);
550
- if (typeof this.expandVisibleSessionList === 'function') {
551
- this.expandVisibleSessionList(0, { ensureActive: true });
552
- }
553
- this.activeSessionMessages = [];
554
- this.resetSessionDetailPagination();
555
- this.resetSessionPreviewMessageRender();
556
- this.activeSessionDetailError = '';
557
- this.activeSessionDetailClipped = false;
558
- this.cancelSessionTimelineSync();
559
- this.sessionTimelineActiveKey = '';
560
- this.clearSessionTimelineRefs();
561
- if (typeof this.scheduleAfterFrame === 'function') {
562
- const selectedSession = this.activeSession;
563
- emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
564
- this.scheduleAfterFrame(() => {
565
- if (this.activeSession !== selectedSession) return;
566
- void this.loadActiveSessionDetail();
567
- });
568
- return;
569
- }
570
- emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
571
- await this.loadActiveSessionDetail();
572
- },
573
-
574
- async loadSessionStandalonePlain() {
575
- if (!this.activeSession) {
576
- this.sessionStandaloneRequestSeq += 1;
577
- this.sessionStandaloneLoading = false;
578
- this.sessionStandaloneText = '';
579
- this.sessionStandaloneTitle = '会话';
580
- this.sessionStandaloneSourceLabel = '';
581
- this.sessionStandaloneError = '';
582
- return;
583
- }
584
-
585
- const requestSeq = ++this.sessionStandaloneRequestSeq;
586
- const sessionSnapshot = this.activeSession;
587
- this.sessionStandaloneLoading = true;
588
- this.sessionStandaloneError = '';
589
- try {
590
- const res = await api('session-plain', {
591
- source: sessionSnapshot.source,
592
- sessionId: sessionSnapshot.sessionId,
593
- filePath: sessionSnapshot.filePath
594
- });
595
-
596
- if (requestSeq !== this.sessionStandaloneRequestSeq) {
597
- return;
598
- }
599
-
600
- if (res.error) {
601
- this.sessionStandaloneText = '';
602
- this.sessionStandaloneError = res.error;
603
- return;
604
- }
605
-
606
- this.sessionStandaloneSourceLabel = res.sourceLabel || sessionSnapshot.sourceLabel || '';
607
- this.sessionStandaloneTitle = res.sessionId || sessionSnapshot.title || '会话';
608
- this.sessionStandaloneText = typeof res.text === 'string' ? res.text : '';
609
- } catch (e) {
610
- if (requestSeq !== this.sessionStandaloneRequestSeq) {
611
- return;
612
- }
613
- this.sessionStandaloneText = '';
614
- this.sessionStandaloneError = '加载会话内容失败: ' + e.message;
615
- } finally {
616
- if (requestSeq === this.sessionStandaloneRequestSeq) {
617
- this.sessionStandaloneLoading = false;
618
- }
619
- }
620
- },
621
-
622
- async loadActiveSessionDetail(options = {}) {
623
- return loadActiveSessionDetailHelper.call(this, api, options);
624
- }
625
- };
626
- }
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' ? 'claude' : (source === 'all' ? 'all' : 'codex');
131
+ const current = Array.isArray(this.sessionPathOptionsMap[targetSource])
132
+ ? this.sessionPathOptionsMap[targetSource]
133
+ : [];
134
+ const merged = mergeWithExisting
135
+ ? this.mergeSessionPathOptions(current, nextOptions)
136
+ : this.mergeSessionPathOptions([], nextOptions);
137
+ this.sessionPathOptionsMap = {
138
+ ...this.sessionPathOptionsMap,
139
+ [targetSource]: merged
140
+ };
141
+ this.refreshSessionPathOptions(targetSource);
142
+ },
143
+
144
+ refreshSessionPathOptions(source) {
145
+ const targetSource = source === 'claude' ? 'claude' : (source === 'all' ? 'all' : 'codex');
146
+ const base = Array.isArray(this.sessionPathOptionsMap[targetSource])
147
+ ? [...this.sessionPathOptionsMap[targetSource]]
148
+ : [];
149
+ const selected = this.normalizeSessionPathValue(this.sessionPathFilter);
150
+ if (selected && !base.some(item => item.toLowerCase() === selected.toLowerCase())) {
151
+ base.unshift(selected);
152
+ }
153
+ if (targetSource === this.sessionFilterSource) {
154
+ this.sessionPathOptions = base;
155
+ }
156
+ },
157
+
158
+ isSessionLoadNativeDialogEnabled() {
159
+ return isSessionLoadNativeDialogEnabled(this);
160
+ },
161
+
162
+ emitSessionLoadNativeDialog(step, details = '') {
163
+ emitSessionLoadNativeDialog(this, step, details);
164
+ },
165
+
166
+ async loadSessionPathOptions(options = {}) {
167
+ const source = options.source === 'claude' ? 'claude' : (options.source === 'all' ? 'all' : 'codex');
168
+ const forceRefresh = !!options.forceRefresh;
169
+ const loaded = !!this.sessionPathOptionsLoadedMap[source];
170
+ if (!forceRefresh && loaded) {
171
+ emitSessionLoadNativeDialog(this, 'loadSessionPathOptions:cache-hit', `source=${source}`);
172
+ if (source === this.sessionFilterSource) {
173
+ this.sessionPathOptionsLoading = false;
174
+ }
175
+ return;
176
+ }
177
+
178
+ const nextSeqMap = {
179
+ ...(this.sessionPathRequestSeqMap || {})
180
+ };
181
+ const requestSeq = (Number(nextSeqMap[source]) || 0) + 1;
182
+ nextSeqMap[source] = requestSeq;
183
+ this.sessionPathRequestSeqMap = nextSeqMap;
184
+ emitSessionLoadNativeDialog(
185
+ this,
186
+ 'loadSessionPathOptions:start',
187
+ `source=${source}\nforceRefresh=${forceRefresh}\nrequestSeq=${requestSeq}`
188
+ );
189
+ if (source === this.sessionFilterSource) {
190
+ this.sessionPathOptionsLoading = true;
191
+ }
192
+ try {
193
+ const res = await api('list-session-paths', {
194
+ source,
195
+ limit: 500,
196
+ forceRefresh
197
+ });
198
+ if (requestSeq !== Number(((this.sessionPathRequestSeqMap || {})[source]) || 0)) {
199
+ emitSessionLoadNativeDialog(
200
+ this,
201
+ 'loadSessionPathOptions:stale-response',
202
+ `source=${source}\nrequestSeq=${requestSeq}`
203
+ );
204
+ return;
205
+ }
206
+ if (res && !res.error && Array.isArray(res.paths)) {
207
+ this.syncSessionPathOptionsForSource(source, res.paths, true);
208
+ this.sessionPathOptionsLoadedMap = {
209
+ ...this.sessionPathOptionsLoadedMap,
210
+ [source]: true
211
+ };
212
+ emitSessionLoadNativeDialog(
213
+ this,
214
+ 'loadSessionPathOptions:success',
215
+ `source=${source}\npaths=${res.paths.length}`
216
+ );
217
+ } else if (res && res.error) {
218
+ emitSessionLoadNativeDialog(
219
+ this,
220
+ 'loadSessionPathOptions:error',
221
+ `source=${source}\nerror=${res.error}`
222
+ );
223
+ }
224
+ } catch (error) {
225
+ emitSessionLoadNativeDialog(
226
+ this,
227
+ 'loadSessionPathOptions:exception',
228
+ `source=${source}\nerror=${error && error.message ? error.message : String(error)}`
229
+ );
230
+ // 路径补全失败不影响会话主流程
231
+ } finally {
232
+ if (
233
+ source === this.sessionFilterSource
234
+ && requestSeq === Number(((this.sessionPathRequestSeqMap || {})[source]) || 0)
235
+ ) {
236
+ this.sessionPathOptionsLoading = false;
237
+ }
238
+ emitSessionLoadNativeDialog(
239
+ this,
240
+ 'loadSessionPathOptions:complete',
241
+ `source=${source}\nrequestSeq=${requestSeq}`
242
+ );
243
+ }
244
+ },
245
+
246
+ onSessionResumeYoloChange() {
247
+ const value = this.sessionResumeWithYolo ? '1' : '0';
248
+ localStorage.setItem('codexmateSessionResumeYolo', value);
249
+ },
250
+
251
+ restoreSessionFilterCache() {
252
+ const urlState = readSessionsFilterUrlState();
253
+ if (urlState) {
254
+ applySessionsFilterUrlState(this, urlState);
255
+ return;
256
+ }
257
+ const sourceCache = localStorage.getItem('codexmateSessionFilterSource');
258
+ const pathCache = localStorage.getItem('codexmateSessionPathFilter');
259
+ const cached = buildSessionFilterCacheState(sourceCache, pathCache);
260
+ this.sessionFilterSource = cached.source;
261
+ this.sessionPathFilter = cached.pathFilter;
262
+ const queryCache = localStorage.getItem('codexmateSessionQuery');
263
+ const roleCache = localStorage.getItem('codexmateSessionRoleFilter');
264
+ const timeCache = localStorage.getItem('codexmateSessionTimePreset');
265
+ this.sessionQuery = typeof queryCache === 'string' ? queryCache : '';
266
+ this.sessionRoleFilter = normalizeSessionRoleFilter(roleCache);
267
+ this.sessionTimePreset = normalizeSessionTimePreset(timeCache);
268
+ this.refreshSessionPathOptions(this.sessionFilterSource);
269
+ },
270
+
271
+ persistSessionFilterCache() {
272
+ const cached = buildSessionFilterCacheState(this.sessionFilterSource, this.sessionPathFilter);
273
+ localStorage.setItem('codexmateSessionFilterSource', cached.source);
274
+ if (cached.pathFilter) {
275
+ localStorage.setItem('codexmateSessionPathFilter', cached.pathFilter);
276
+ } else {
277
+ localStorage.removeItem('codexmateSessionPathFilter');
278
+ }
279
+ if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
280
+ localStorage.setItem('codexmateSessionQuery', this.sessionQuery);
281
+ } else {
282
+ localStorage.removeItem('codexmateSessionQuery');
283
+ }
284
+ localStorage.setItem('codexmateSessionRoleFilter', normalizeSessionRoleFilter(this.sessionRoleFilter));
285
+ localStorage.setItem('codexmateSessionTimePreset', normalizeSessionTimePreset(this.sessionTimePreset));
286
+ },
287
+
288
+ normalizeSessionPinnedMap(raw) {
289
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
290
+ return {};
291
+ }
292
+ const next = {};
293
+ for (const [key, value] of Object.entries(raw)) {
294
+ if (!key) continue;
295
+ const numeric = Number(value);
296
+ if (!Number.isFinite(numeric) || numeric <= 0) continue;
297
+ next[key] = Math.floor(numeric);
298
+ }
299
+ return next;
300
+ },
301
+
302
+ restoreSessionPinnedMap() {
303
+ const cached = localStorage.getItem('codexmateSessionPinnedMap');
304
+ if (!cached) {
305
+ this.sessionPinnedMap = {};
306
+ return;
307
+ }
308
+ try {
309
+ const parsed = JSON.parse(cached);
310
+ this.sessionPinnedMap = this.normalizeSessionPinnedMap(parsed);
311
+ } catch (_) {
312
+ this.sessionPinnedMap = {};
313
+ localStorage.removeItem('codexmateSessionPinnedMap');
314
+ }
315
+ },
316
+
317
+ persistSessionPinnedMap() {
318
+ const payload = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
319
+ ? this.sessionPinnedMap
320
+ : {};
321
+ localStorage.setItem('codexmateSessionPinnedMap', JSON.stringify(payload));
322
+ },
323
+
324
+ shouldPruneSessionPinnedMap(sessions = this.sessionsList) {
325
+ if (!Array.isArray(sessions) || sessions.length === 0) {
326
+ return false;
327
+ }
328
+ if (this.sessionFilterSource !== 'all') {
329
+ return false;
330
+ }
331
+ if (this.sessionPathFilter) {
332
+ return false;
333
+ }
334
+ if (this.sessionQuery && isSessionQueryEnabled(this.sessionFilterSource)) {
335
+ return false;
336
+ }
337
+ if (this.sessionRoleFilter && this.sessionRoleFilter !== 'all') {
338
+ return false;
339
+ }
340
+ if (this.sessionTimePreset && this.sessionTimePreset !== 'all') {
341
+ return false;
342
+ }
343
+ return true;
344
+ },
345
+
346
+ pruneSessionPinnedMap(sessions = this.sessionsList) {
347
+ const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
348
+ ? this.sessionPinnedMap
349
+ : {};
350
+ const list = Array.isArray(sessions) ? sessions : [];
351
+ if (Object.keys(current).length === 0 || !this.shouldPruneSessionPinnedMap(list)) {
352
+ return;
353
+ }
354
+ const validKeys = new Set(list.map((session) => this.getSessionExportKey(session)).filter(Boolean));
355
+ const next = {};
356
+ let changed = false;
357
+ for (const [key, value] of Object.entries(current)) {
358
+ if (!validKeys.has(key)) {
359
+ changed = true;
360
+ continue;
361
+ }
362
+ next[key] = value;
363
+ }
364
+ if (!changed) {
365
+ return;
366
+ }
367
+ this.sessionPinnedMap = next;
368
+ this.persistSessionPinnedMap();
369
+ },
370
+
371
+ getSessionPinTimestamp(session) {
372
+ if (!session) return 0;
373
+ const key = this.getSessionExportKey(session);
374
+ if (!key) return 0;
375
+ const raw = this.sessionPinnedMap && this.sessionPinnedMap[key];
376
+ const numeric = Number(raw);
377
+ return Number.isFinite(numeric) && numeric > 0 ? Math.floor(numeric) : 0;
378
+ },
379
+
380
+ isSessionPinned(session) {
381
+ return this.getSessionPinTimestamp(session) > 0;
382
+ },
383
+
384
+ toggleSessionPin(session) {
385
+ if (!session) return;
386
+ const key = this.getSessionExportKey(session);
387
+ if (!key) return;
388
+ const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
389
+ ? this.sessionPinnedMap
390
+ : {};
391
+ const next = { ...current };
392
+ if (next[key]) {
393
+ delete next[key];
394
+ } else {
395
+ next[key] = Date.now();
396
+ }
397
+ this.sessionPinnedMap = next;
398
+ this.persistSessionPinnedMap();
399
+ },
400
+
401
+ removeSessionPin(session) {
402
+ if (!session) return;
403
+ const key = this.getSessionExportKey(session);
404
+ if (!key) return;
405
+ const current = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
406
+ ? this.sessionPinnedMap
407
+ : {};
408
+ if (!current[key]) return;
409
+ const next = { ...current };
410
+ delete next[key];
411
+ this.sessionPinnedMap = next;
412
+ this.persistSessionPinnedMap();
413
+ },
414
+
415
+ async onSessionSourceChange() {
416
+ this.refreshSessionPathOptions(this.sessionFilterSource);
417
+ this.persistSessionFilterCache();
418
+ syncSessionsFilterUrl(this);
419
+ await this.loadSessions();
420
+ },
421
+
422
+ async onSessionPathFilterChange() {
423
+ this.persistSessionFilterCache();
424
+ syncSessionsFilterUrl(this);
425
+ await this.loadSessions();
426
+ },
427
+
428
+ async onSessionFilterChange() {
429
+ this.persistSessionFilterCache();
430
+ syncSessionsFilterUrl(this);
431
+ await this.loadSessions();
432
+ },
433
+
434
+ async clearSessionFilters() {
435
+ this.sessionFilterSource = 'all';
436
+ this.sessionPathFilter = '';
437
+ this.sessionQuery = '';
438
+ this.sessionRoleFilter = 'all';
439
+ this.sessionTimePreset = 'all';
440
+ this.persistSessionFilterCache();
441
+ syncSessionsFilterUrl(this);
442
+ await this.onSessionSourceChange();
443
+ },
444
+
445
+ copySessionsFilterShareUrl() {
446
+ const url = buildSessionsFilterShareUrl(this);
447
+ if (!url) {
448
+ this.showMessage('无法生成链接', 'error');
449
+ return;
450
+ }
451
+ const ok = typeof this.fallbackCopyText === 'function' ? this.fallbackCopyText(url) : false;
452
+ if (ok) {
453
+ this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.ok') : 'Copied', 'success');
454
+ return;
455
+ }
456
+ this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.fail') : 'Copy failed', 'error');
457
+ },
458
+
459
+ normalizeSessionMessage(message) {
460
+ const fallback = {
461
+ role: 'assistant',
462
+ normalizedRole: 'assistant',
463
+ roleLabel: 'Assistant',
464
+ text: typeof message === 'string' ? message : '',
465
+ timestamp: ''
466
+ };
467
+ const safeMessage = message && typeof message === 'object' ? message : fallback;
468
+ const normalizedRole = normalizeSessionMessageRole(
469
+ safeMessage.normalizedRole || safeMessage.role
470
+ );
471
+ const roleLabel = normalizedRole === 'user'
472
+ ? 'User'
473
+ : (normalizedRole === 'system' ? 'System' : 'Assistant');
474
+ return {
475
+ ...safeMessage,
476
+ role: normalizedRole,
477
+ normalizedRole,
478
+ roleLabel
479
+ };
480
+ },
481
+
482
+ getRecordKey(message) {
483
+ if (!message || !Number.isInteger(message.recordLineIndex) || message.recordLineIndex < 0) {
484
+ return '';
485
+ }
486
+ return String(message.recordLineIndex);
487
+ },
488
+
489
+ getRecordRenderKey(message, idx) {
490
+ const recordKey = this.getRecordKey(message);
491
+ if (recordKey) {
492
+ return `record-${recordKey}`;
493
+ }
494
+ return `record-fallback-${idx}-${message && message.timestamp ? message.timestamp : ''}`;
495
+ },
496
+
497
+ syncActiveSessionMessageCount(messageCount) {
498
+ if (!Number.isFinite(messageCount) || messageCount < 0) return;
499
+ if (this.activeSession) {
500
+ this.activeSession.messageCount = messageCount;
501
+ }
502
+ const activeKey = this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
503
+ if (!activeKey) return;
504
+ const matched = this.sessionsList.find(item => this.getSessionExportKey(item) === activeKey);
505
+ if (matched) {
506
+ matched.messageCount = messageCount;
507
+ }
508
+ },
509
+
510
+ invalidateSessionsUsageData(options = {}) {
511
+ this.sessionsUsageLoadedOnce = false;
512
+ this.sessionsUsageLoadedLimit = 0;
513
+ this.sessionsUsageError = '';
514
+ if (options.preserveList !== true) {
515
+ this.sessionsUsageList = [];
516
+ }
517
+ },
518
+
519
+ setSessionsUsageTimeRange(nextRange) {
520
+ const normalized = typeof nextRange === 'string' ? nextRange.trim().toLowerCase() : '';
521
+ const range = normalized === 'all' ? 'all' : (normalized === '30d' ? '30d' : '7d');
522
+ this.sessionsUsageTimeRange = range;
523
+ void this.loadSessionsUsage({ range });
524
+ },
525
+
526
+ async loadSessionsUsage(options = {}) {
527
+ if (this.sessionsUsageLoading) return;
528
+ const normalizedRange = typeof options.range === 'string'
529
+ ? options.range.trim().toLowerCase()
530
+ : (typeof this.sessionsUsageTimeRange === 'string' ? this.sessionsUsageTimeRange.trim().toLowerCase() : '');
531
+ const range = normalizedRange === 'all' ? 'all' : (normalizedRange === '30d' ? '30d' : '7d');
532
+ const defaultLimit = range === 'all' ? 2000 : (range === '30d' ? 1200 : 600);
533
+ const rawLimit = Number(options.limit);
534
+ const limit = Number.isFinite(rawLimit) ? Math.max(1, Math.min(rawLimit, 2000)) : defaultLimit;
535
+ const loadedLimit = Number(this.sessionsUsageLoadedLimit || 0);
536
+ if (this.sessionsUsageLoadedOnce && !options.forceRefresh && loadedLimit >= limit) {
537
+ return;
538
+ }
539
+ this.sessionsUsageLoading = true;
540
+ this.sessionsUsageError = '';
541
+ let loadSucceeded = false;
542
+ try {
543
+ const res = await api('list-sessions-usage', {
544
+ source: 'all',
545
+ limit,
546
+ forceRefresh: !!options.forceRefresh
547
+ });
548
+ if (res.error) {
549
+ this.sessionsUsageError = res.error;
550
+ this.showMessage(res.error, 'error');
551
+ return;
552
+ }
553
+ this.sessionsUsageList = Array.isArray(res.sessions) ? res.sessions : [];
554
+ loadSucceeded = true;
555
+ } catch (e) {
556
+ this.sessionsUsageError = '加载 usage 统计失败';
557
+ this.showMessage('加载 usage 统计失败', 'error');
558
+ } finally {
559
+ this.sessionsUsageLoading = false;
560
+ if (loadSucceeded) {
561
+ this.sessionsUsageLoadedOnce = true;
562
+ this.sessionsUsageLoadedLimit = limit;
563
+ }
564
+ }
565
+ },
566
+
567
+ async loadSessions(options = {}) {
568
+ const result = await loadSessionsHelper.call(this, api, options || {});
569
+ this.pruneSessionPinnedMap(this.sessionsList);
570
+ return result;
571
+ },
572
+
573
+ async selectSession(session) {
574
+ if (!session) {
575
+ emitSessionLoadNativeDialog(this, 'selectSession:skip-empty');
576
+ return;
577
+ }
578
+ emitSessionLoadNativeDialog(
579
+ this,
580
+ 'selectSession:start',
581
+ `sessionId=${session.sessionId || ''}\nsource=${session.source || ''}`
582
+ );
583
+ const isSameSession = this.activeSession
584
+ && this.getSessionExportKey(this.activeSession) === this.getSessionExportKey(session);
585
+ if (isSameSession) {
586
+ emitSessionLoadNativeDialog(this, 'selectSession:same-session', `sessionId=${session.sessionId || ''}`);
587
+ if (this.sessionDetailLoading) {
588
+ emitSessionLoadNativeDialog(this, 'selectSession:skip-detail-loading', `sessionId=${session.sessionId || ''}`);
589
+ return;
590
+ }
591
+ const currentMessages = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages : [];
592
+ if (currentMessages.length > 0) {
593
+ emitSessionLoadNativeDialog(
594
+ this,
595
+ 'selectSession:skip-existing-messages',
596
+ `sessionId=${session.sessionId || ''}\nmessages=${currentMessages.length}`
597
+ );
598
+ return;
599
+ }
600
+ if (typeof this.scheduleAfterFrame === 'function') {
601
+ const selectedSession = this.activeSession;
602
+ emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
603
+ this.scheduleAfterFrame(() => {
604
+ if (this.activeSession !== selectedSession) return;
605
+ void this.loadActiveSessionDetail();
606
+ });
607
+ return;
608
+ }
609
+ emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
610
+ await this.loadActiveSessionDetail();
611
+ return;
612
+ }
613
+ this.activeSession = session;
614
+ emitSessionLoadNativeDialog(this, 'selectSession:activate', `sessionId=${session.sessionId || ''}`);
615
+ if (typeof this.expandVisibleSessionList === 'function') {
616
+ this.expandVisibleSessionList(0, { ensureActive: true });
617
+ }
618
+ this.activeSessionMessages = [];
619
+ this.resetSessionDetailPagination();
620
+ this.resetSessionPreviewMessageRender();
621
+ this.activeSessionDetailError = '';
622
+ this.activeSessionDetailClipped = false;
623
+ this.cancelSessionTimelineSync();
624
+ this.sessionTimelineActiveKey = '';
625
+ this.clearSessionTimelineRefs();
626
+ if (typeof this.scheduleAfterFrame === 'function') {
627
+ const selectedSession = this.activeSession;
628
+ emitSessionLoadNativeDialog(this, 'selectSession:schedule-detail', `sessionId=${session.sessionId || ''}`);
629
+ this.scheduleAfterFrame(() => {
630
+ if (this.activeSession !== selectedSession) return;
631
+ void this.loadActiveSessionDetail();
632
+ });
633
+ return;
634
+ }
635
+ emitSessionLoadNativeDialog(this, 'selectSession:load-detail-now', `sessionId=${session.sessionId || ''}`);
636
+ await this.loadActiveSessionDetail();
637
+ },
638
+
639
+ async loadSessionStandalonePlain() {
640
+ if (!this.activeSession) {
641
+ this.sessionStandaloneRequestSeq += 1;
642
+ this.sessionStandaloneLoading = false;
643
+ this.sessionStandaloneText = '';
644
+ this.sessionStandaloneTitle = '会话';
645
+ this.sessionStandaloneSourceLabel = '';
646
+ this.sessionStandaloneError = '';
647
+ return;
648
+ }
649
+
650
+ const requestSeq = ++this.sessionStandaloneRequestSeq;
651
+ const sessionSnapshot = this.activeSession;
652
+ this.sessionStandaloneLoading = true;
653
+ this.sessionStandaloneError = '';
654
+ try {
655
+ const res = await api('session-plain', {
656
+ source: sessionSnapshot.source,
657
+ sessionId: sessionSnapshot.sessionId,
658
+ filePath: sessionSnapshot.filePath
659
+ });
660
+
661
+ if (requestSeq !== this.sessionStandaloneRequestSeq) {
662
+ return;
663
+ }
664
+
665
+ if (res.error) {
666
+ this.sessionStandaloneText = '';
667
+ this.sessionStandaloneError = res.error;
668
+ return;
669
+ }
670
+
671
+ this.sessionStandaloneSourceLabel = res.sourceLabel || sessionSnapshot.sourceLabel || '';
672
+ this.sessionStandaloneTitle = res.sessionId || sessionSnapshot.title || '会话';
673
+ this.sessionStandaloneText = typeof res.text === 'string' ? res.text : '';
674
+ } catch (e) {
675
+ if (requestSeq !== this.sessionStandaloneRequestSeq) {
676
+ return;
677
+ }
678
+ this.sessionStandaloneText = '';
679
+ this.sessionStandaloneError = '加载会话内容失败: ' + e.message;
680
+ } finally {
681
+ if (requestSeq === this.sessionStandaloneRequestSeq) {
682
+ this.sessionStandaloneLoading = false;
683
+ }
684
+ }
685
+ },
686
+
687
+ async loadActiveSessionDetail(options = {}) {
688
+ return loadActiveSessionDetailHelper.call(this, api, options);
689
+ }
690
+ };
691
+ }