codexmate 0.0.21 → 0.0.22

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 (114) hide show
  1. package/README.md +389 -284
  2. package/README.zh.md +321 -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 +575 -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 +198 -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 +161 -149
  52. package/web-ui/modules/app.methods.navigation.mjs +619 -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 +626 -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 +405 -412
  63. package/web-ui/modules/app.methods.task-orchestration.mjs +471 -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 +1609 -0
  67. package/web-ui/modules/plugins.computed.mjs +220 -0
  68. package/web-ui/modules/plugins.methods.mjs +620 -0
  69. package/web-ui/modules/plugins.storage.mjs +37 -0
  70. package/web-ui/modules/skills.computed.mjs +107 -107
  71. package/web-ui/modules/skills.methods.mjs +481 -481
  72. package/web-ui/partials/index/layout-footer.html +13 -13
  73. package/web-ui/partials/index/layout-header.html +461 -402
  74. package/web-ui/partials/index/modal-config-template-agents.html +175 -125
  75. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  76. package/web-ui/partials/index/modal-health-check.html +72 -72
  77. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  78. package/web-ui/partials/index/modal-skills.html +200 -184
  79. package/web-ui/partials/index/modals-basic.html +165 -156
  80. package/web-ui/partials/index/panel-config-claude.html +138 -126
  81. package/web-ui/partials/index/panel-config-codex.html +234 -237
  82. package/web-ui/partials/index/panel-config-openclaw.html +78 -78
  83. package/web-ui/partials/index/panel-docs.html +147 -130
  84. package/web-ui/partials/index/panel-market.html +174 -174
  85. package/web-ui/partials/index/panel-orchestration.html +397 -397
  86. package/web-ui/partials/index/panel-plugins.html +243 -0
  87. package/web-ui/partials/index/panel-sessions.html +292 -292
  88. package/web-ui/partials/index/panel-settings.html +258 -190
  89. package/web-ui/partials/index/panel-usage.html +353 -213
  90. package/web-ui/session-helpers.mjs +573 -559
  91. package/web-ui/source-bundle.cjs +233 -233
  92. package/web-ui/styles/base-theme.css +264 -271
  93. package/web-ui/styles/controls-forms.css +362 -360
  94. package/web-ui/styles/docs-panel.css +247 -182
  95. package/web-ui/styles/feedback.css +108 -108
  96. package/web-ui/styles/health-check-dialog.css +144 -144
  97. package/web-ui/styles/layout-shell.css +596 -376
  98. package/web-ui/styles/modals-core.css +464 -464
  99. package/web-ui/styles/navigation-panels.css +382 -348
  100. package/web-ui/styles/openclaw-structured.css +266 -266
  101. package/web-ui/styles/plugins-panel.css +518 -0
  102. package/web-ui/styles/responsive.css +456 -450
  103. package/web-ui/styles/sessions-list.css +400 -400
  104. package/web-ui/styles/sessions-preview.css +411 -411
  105. package/web-ui/styles/sessions-toolbar-trash.css +268 -243
  106. package/web-ui/styles/sessions-usage.css +851 -628
  107. package/web-ui/styles/settings-panel.css +166 -0
  108. package/web-ui/styles/skills-list.css +303 -296
  109. package/web-ui/styles/skills-market.css +396 -335
  110. package/web-ui/styles/task-orchestration.css +776 -776
  111. package/web-ui/styles/titles-cards.css +408 -408
  112. package/web-ui/styles.css +20 -18
  113. package/web-ui.html +17 -17
  114. package/README.en.md +0 -349
@@ -1,581 +1,614 @@
1
- export const DEFAULT_SESSION_LIST_LIMIT = 200;
2
- export const DEFAULT_SESSION_LIST_FAST_LIMIT = 20;
3
-
4
- function shouldUseFastSessionBrowseLimit(options = {}) {
5
- if (options.forceRefresh) {
6
- return false;
7
- }
8
- const normalizedSource = normalizeSessionSource(options.source, 'all');
9
- if (normalizedSource !== 'all') {
10
- return false;
11
- }
12
- const pathFilter = normalizeSessionPathFilter(options.pathFilter);
13
- if (pathFilter) {
14
- return false;
15
- }
16
- const query = typeof options.query === 'string' ? options.query.trim() : '';
17
- if (query) {
18
- return false;
19
- }
20
- const roleFilter = typeof options.roleFilter === 'string' ? options.roleFilter.trim().toLowerCase() : 'all';
21
- if (roleFilter && roleFilter !== 'all') {
22
- return false;
23
- }
24
- const timeRangePreset = typeof options.timeRangePreset === 'string'
25
- ? options.timeRangePreset.trim().toLowerCase()
26
- : 'all';
27
- return !timeRangePreset || timeRangePreset === 'all';
28
- }
29
-
30
- export function isSessionQueryEnabled(source) {
31
- const normalized = normalizeSessionSource(source, '');
32
- return normalized === 'codex' || normalized === 'claude' || normalized === 'all';
33
- }
34
-
35
- export function normalizeSessionSource(source, fallback = 'all') {
36
- const normalized = typeof source === 'string'
37
- ? source.trim().toLowerCase()
38
- : '';
39
- if (normalized === 'codex' || normalized === 'claude' || normalized === 'all') {
40
- return normalized;
41
- }
42
- return fallback;
43
- }
44
-
45
- export function normalizeSessionPathFilter(pathFilter) {
46
- return typeof pathFilter === 'string' ? pathFilter.trim() : '';
47
- }
48
-
49
- function isConcreteSessionModelName(value) {
50
- if (typeof value !== 'string') {
51
- return false;
52
- }
53
- const normalized = value.trim();
54
- if (!normalized) {
55
- return false;
56
- }
57
- return normalized.toLowerCase() !== '<synthetic>';
58
- }
59
-
60
- function collectSessionModelNames(session) {
61
- if (!session || typeof session !== 'object') {
62
- return [];
63
- }
64
- const values = Array.isArray(session.models)
65
- ? [...session.models, session.model, session.modelName, session.modelId]
66
- : [session.model, session.modelName, session.modelId];
67
- const models = [];
68
- for (const value of values) {
69
- if (!isConcreteSessionModelName(value)) {
70
- continue;
71
- }
72
- const normalized = value.trim();
73
- if (models.includes(normalized)) {
74
- continue;
75
- }
76
- models.push(normalized);
77
- }
78
- return models;
79
- }
80
-
81
- export function buildSessionFilterCacheState(source, pathFilter) {
82
- return {
83
- source: normalizeSessionSource(source, 'all'),
84
- pathFilter: normalizeSessionPathFilter(pathFilter)
85
- };
86
- }
87
-
88
- export function buildSessionListParams(options = {}) {
89
- const fallbackLimit = shouldUseFastSessionBrowseLimit(options)
90
- ? DEFAULT_SESSION_LIST_FAST_LIMIT
91
- : DEFAULT_SESSION_LIST_LIMIT;
92
- const {
93
- source = 'all',
94
- pathFilter = '',
95
- query = '',
96
- roleFilter = 'all',
97
- timeRangePreset = 'all',
98
- limit = fallbackLimit,
99
- forceRefresh = false
100
- } = options;
101
- const normalizedSource = normalizeSessionSource(source, 'all');
102
- const normalizedPathFilter = normalizeSessionPathFilter(pathFilter);
103
- const queryValue = isSessionQueryEnabled(normalizedSource) ? query : '';
104
- return {
105
- source: normalizedSource,
106
- pathFilter: normalizedPathFilter,
107
- query: queryValue,
108
- queryMode: 'and',
109
- queryScope: 'content',
110
- contentScanLimit: 50,
111
- roleFilter,
112
- timeRangePreset,
113
- limit,
114
- forceRefresh: !!forceRefresh
115
- };
116
- }
117
-
118
- export function normalizeSessionMessageRole(role) {
119
- const value = typeof role === 'string' ? role.trim().toLowerCase() : '';
120
- if (value === 'user' || value === 'assistant' || value === 'system') {
121
- return value;
122
- }
123
- return 'assistant';
124
- }
125
-
126
- function toRoleMeta(role) {
127
- if (role === 'user') {
128
- return { role: 'user', roleLabel: 'User', roleShort: 'U' };
129
- }
130
- if (role === 'assistant') {
131
- return { role: 'assistant', roleLabel: 'Assistant', roleShort: 'A' };
132
- }
133
- if (role === 'system') {
134
- return { role: 'system', roleLabel: 'System', roleShort: 'S' };
135
- }
136
- return { role: 'mixed', roleLabel: 'Mixed', roleShort: 'M' };
137
- }
138
-
139
- function clampTimelinePercent(percent) {
140
- return Math.max(6, Math.min(94, percent));
141
- }
142
-
143
- export function formatSessionTimelineTimestamp(timestamp) {
144
- const value = typeof timestamp === 'string' ? timestamp.trim() : '';
145
- if (!value) return '';
146
-
147
- const matched = value.match(/^(\d{4})-(\d{2})-(\d{2})[T\s](\d{2}):(\d{2})(?::(\d{2}))?/);
148
- if (matched) {
149
- const second = matched[6] || '00';
150
- return `${matched[2]}-${matched[3]} ${matched[4]}:${matched[5]}:${second}`;
151
- }
152
-
153
- return value;
154
- }
155
-
156
- function normalizeUsageRange(range) {
157
- const normalized = typeof range === 'string' ? range.trim().toLowerCase() : '7d';
158
- if (normalized === '30d' || normalized === 'all') {
159
- return normalized;
160
- }
161
- return '7d';
162
- }
163
-
164
- function toUtcDayStartMs(value) {
165
- const stamp = new Date(value);
166
- return Date.UTC(stamp.getUTCFullYear(), stamp.getUTCMonth(), stamp.getUTCDate());
167
- }
168
-
169
- function formatUtcDayKey(value) {
170
- const stamp = new Date(value);
171
- return `${stamp.getUTCFullYear()}-${String(stamp.getUTCMonth() + 1).padStart(2, '0')}-${String(stamp.getUTCDate()).padStart(2, '0')}`;
172
- }
173
-
174
- function buildUsageBuckets(normalizedSessions, options = {}) {
175
- const range = normalizeUsageRange(options.range);
176
- const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
177
- const dayMs = 24 * 60 * 60 * 1000;
178
- const buckets = [];
179
-
180
- if (range === 'all') {
181
- const validDayStarts = normalizedSessions
182
- .map((session) => toUtcDayStartMs(session.updatedAtMs))
183
- .filter((value) => Number.isFinite(value));
184
- const firstDayStart = validDayStarts.length ? Math.min(...validDayStarts) : toUtcDayStartMs(now);
185
- const lastDayStart = validDayStarts.length ? Math.max(...validDayStarts) : toUtcDayStartMs(now);
186
- for (let stamp = firstDayStart; stamp <= lastDayStart; stamp += dayMs) {
187
- const key = formatUtcDayKey(stamp);
188
- buckets.push({
189
- key,
190
- label: key.slice(5),
191
- codex: 0,
192
- claude: 0,
193
- totalMessages: 0,
194
- totalSessions: 0
195
- });
196
- }
197
- return { range, buckets };
198
- }
199
-
200
- const rangeDays = range === '30d' ? 30 : 7;
201
- for (let i = rangeDays - 1; i >= 0; i -= 1) {
202
- const stamp = new Date(now - (i * dayMs));
203
- const key = formatUtcDayKey(stamp);
204
- buckets.push({
205
- key,
206
- label: key.slice(5),
207
- codex: 0,
208
- claude: 0,
209
- totalMessages: 0,
210
- totalSessions: 0
211
- });
212
- }
213
- return { range, buckets };
214
- }
215
-
216
- export function buildUsageChartGroups(sessions = [], options = {}) {
217
- const list = Array.isArray(sessions) ? sessions : [];
218
- const normalizedSessions = [];
219
- for (const [sessionIndex, session] of list.entries()) {
220
- if (!session || typeof session !== 'object') continue;
221
- const source = normalizeSessionSource(session.source, '');
222
- if (source !== 'codex' && source !== 'claude') continue;
223
- const updatedAtMs = Date.parse(session.updatedAt || '');
224
- if (!Number.isFinite(updatedAtMs)) continue;
225
- const createdAtMs = Date.parse(session.createdAt || '');
226
- const sessionStartedAtMs = Number.isFinite(createdAtMs) ? createdAtMs : updatedAtMs;
227
- const sessionEndedAtMs = Math.max(updatedAtMs, sessionStartedAtMs);
228
- normalizedSessions.push({
229
- session,
230
- sessionIndex,
231
- source,
232
- updatedAtMs,
233
- createdAtMs,
234
- sessionStartedAtMs,
235
- sessionEndedAtMs,
236
- bucketKey: formatUtcDayKey(updatedAtMs)
237
- });
238
- }
239
- const { range, buckets } = buildUsageBuckets(normalizedSessions, options);
240
- const bucketMap = new Map(buckets.map((bucket) => [bucket.key, bucket]));
241
- let codexTotal = 0;
242
- let claudeTotal = 0;
243
- let messageTotal = 0;
244
- let totalTokens = 0;
245
- let totalContextWindow = 0;
246
- let activeDurationMs = 0;
247
- let earliestSessionMs = Number.POSITIVE_INFINITY;
248
- let latestSessionMs = 0;
249
- const pathMap = new Map();
250
- const modelMap = new Map();
251
- const missingModelProviderMap = new Map();
252
- const missingModelSessionMap = new Map();
253
- const sourceMessageTotals = { codex: 0, claude: 0 };
254
- const missingModelSourceTotals = { codex: 0, claude: 0 };
255
- let missingModelSessions = 0;
256
- let providerOnlySessions = 0;
257
- const hourCounts = Array.from({ length: 24 }, (_, hour) => ({
258
- key: String(hour).padStart(2, '0'),
259
- label: String(hour).padStart(2, '0'),
260
- count: 0
261
- }));
262
- const weekdayLabels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
263
- const weekdayCounts = Array.from({ length: 7 }, (_, index) => ({
264
- key: String(index),
265
- label: weekdayLabels[index],
266
- count: 0
267
- }));
268
- const recentSessions = [];
269
- const topSessionsByMessages = [];
270
- const filteredSessions = [];
271
-
272
- for (const normalized of normalizedSessions) {
273
- const { session, sessionIndex, source, updatedAtMs, sessionStartedAtMs, sessionEndedAtMs, bucketKey } = normalized;
274
- const stamp = new Date(updatedAtMs);
275
- const bucket = bucketMap.get(bucketKey);
276
- if (!bucket) continue;
277
- const sessionModels = collectSessionModelNames(session);
278
- if (sessionModels.length === 0) continue;
279
- filteredSessions.push(session);
280
- const messageCount = Number.isFinite(Number(session.messageCount))
281
- ? Math.max(0, Math.floor(Number(session.messageCount)))
282
- : 0;
283
- const sessionTotalTokens = Number.isFinite(Number(session.totalTokens))
284
- ? Math.max(0, Math.floor(Number(session.totalTokens)))
285
- : 0;
286
- const sessionContextWindow = Number.isFinite(Number(session.contextWindow))
287
- ? Math.max(0, Math.floor(Number(session.contextWindow)))
288
- : 0;
289
- bucket.totalSessions += 1;
290
- bucket.totalMessages += messageCount;
291
- if (source === 'codex') {
292
- bucket.codex += 1;
293
- codexTotal += 1;
294
- } else {
295
- bucket.claude += 1;
296
- claudeTotal += 1;
297
- }
298
- messageTotal += messageCount;
299
- totalTokens += sessionTotalTokens;
300
- totalContextWindow += sessionContextWindow;
301
- sourceMessageTotals[source] += messageCount;
302
- activeDurationMs += Math.max(0, sessionEndedAtMs - sessionStartedAtMs);
303
- earliestSessionMs = Math.min(earliestSessionMs, sessionStartedAtMs);
304
- latestSessionMs = Math.max(latestSessionMs, sessionEndedAtMs);
305
-
306
- const utcHour = stamp.getUTCHours();
307
- if (hourCounts[utcHour]) {
308
- hourCounts[utcHour].count += 1;
309
- }
310
- const dayIndex = (stamp.getUTCDay() + 6) % 7;
311
- if (weekdayCounts[dayIndex]) {
312
- weekdayCounts[dayIndex].count += 1;
313
- }
314
-
315
- const cwd = normalizeSessionPathFilter(session.cwd);
316
- if (cwd) {
317
- const prev = pathMap.get(cwd) || { count: 0, messageTotal: 0, updatedAtMs: 0 };
318
- pathMap.set(cwd, {
319
- count: prev.count + 1,
320
- messageTotal: prev.messageTotal + messageCount,
321
- updatedAtMs: Math.max(prev.updatedAtMs, updatedAtMs)
322
- });
323
- }
324
-
325
- const sourceLabel = source === 'codex' ? 'Codex' : 'Claude Code';
326
- const normalizedTitle = typeof session.title === 'string' && session.title.trim()
327
- ? session.title.trim()
328
- : (typeof session.sessionId === 'string' && session.sessionId.trim() ? session.sessionId.trim() : '未命名会话');
329
- for (const modelId of sessionModels) {
330
- const prev = modelMap.get(modelId) || {
331
- count: 0,
332
- messageTotal: 0,
333
- tokenTotal: 0,
334
- sources: new Set()
335
- };
336
- prev.count += 1;
337
- prev.messageTotal += messageCount;
338
- prev.tokenTotal += sessionTotalTokens;
339
- prev.sources.add(source);
340
- modelMap.set(modelId, prev);
341
- }
342
-
343
- const sessionEntry = {
344
- key: [
345
- source,
346
- session.sessionId || '',
347
- session.filePath || normalizedTitle,
348
- String(updatedAtMs),
349
- String(messageCount),
350
- String(sessionIndex)
351
- ].join(':'),
352
- title: normalizedTitle,
353
- source,
354
- sourceLabel,
355
- cwd,
356
- messageCount,
357
- updatedAt: session.updatedAt || '',
358
- updatedAtMs,
359
- updatedAtLabel: formatSessionTimelineTimestamp(session.updatedAt || ''),
360
- hasExactMessageCount: session.__messageCountExact === true
361
- };
362
- recentSessions.push(sessionEntry);
363
- topSessionsByMessages.push({ ...sessionEntry });
364
- }
365
-
366
- const totalSessions = codexTotal + claudeTotal;
367
- const sourceShare = [
368
- { key: 'codex', label: 'Codex', value: codexTotal },
369
- { key: 'claude', label: 'Claude', value: claudeTotal }
370
- ].map((item) => ({
371
- ...item,
372
- percent: totalSessions > 0 ? Math.round((item.value / totalSessions) * 100) : 0,
373
- messageTotal: sourceMessageTotals[item.key] || 0,
374
- messagePercent: messageTotal > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / messageTotal) * 100) : 0,
375
- avgMessages: item.value > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / item.value) * 10) / 10 : 0
376
- }));
377
-
378
- const topPaths = [...pathMap.entries()]
379
- .sort((a, b) => b[1].count - a[1].count || b[1].messageTotal - a[1].messageTotal || a[0].localeCompare(b[0], 'zh-Hans-CN'))
380
- .slice(0, 5)
381
- .map(([pathValue, meta]) => ({
382
- path: pathValue,
383
- count: meta.count,
384
- messageTotal: meta.messageTotal,
385
- updatedAtLabel: meta.updatedAtMs ? formatSessionTimelineTimestamp(new Date(meta.updatedAtMs).toISOString()) : ''
386
- }));
387
-
388
- const usedModels = [...modelMap.entries()]
389
- .sort((a, b) => b[1].count - a[1].count)
390
- .map(([modelId, meta]) => {
391
- const sourceLabels = [...meta.sources]
392
- .sort((a, b) => a.localeCompare(b, 'en-US'))
393
- .map((source) => (source === 'codex' ? 'Codex' : 'Claude Code'));
394
- return {
395
- key: modelId,
396
- model: modelId,
397
- count: meta.count,
398
- messageTotal: meta.messageTotal,
399
- tokenTotal: meta.tokenTotal,
400
- sourceLabels
401
- };
402
- });
403
-
404
- const sortedRecentSessions = recentSessions
405
- .sort((a, b) => b.updatedAtMs - a.updatedAtMs || b.messageCount - a.messageCount || a.title.localeCompare(b.title, 'zh-Hans-CN'))
406
- .slice(0, 6);
407
-
408
- const missingModelProviders = [...missingModelProviderMap.values()]
409
- .sort((a, b) => b.count - a.count || a.label.localeCompare(b.label, 'zh-Hans-CN'));
410
- const missingModelSessionsPreview = [...missingModelSessionMap.values()]
411
- .sort((a, b) => b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
412
- .slice(0, 5);
413
-
414
- const modelCoverage = {
415
- totalSessions,
416
- modeledSessions: Math.max(0, totalSessions - missingModelSessions),
417
- missingModelSessions,
418
- providerOnlySessions,
419
- missingModelSourceTotals,
420
- missingModelProviders,
421
- missingModelSessionsPreview,
422
- coveragePercent: totalSessions > 0 ? Math.round(((totalSessions - missingModelSessions) / totalSessions) * 100) : 0
423
- };
424
-
425
- const sortedTopSessionsByMessages = topSessionsByMessages
426
- .sort((a, b) => b.messageCount - a.messageCount || b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
427
- .slice(0, 6);
428
-
429
- const maxSessionBucket = buckets.reduce((max, item) => Math.max(max, item.totalSessions), 0);
430
- const maxMessageBucket = buckets.reduce((max, item) => Math.max(max, item.totalMessages), 0);
431
- const maxHourCount = hourCounts.reduce((max, item) => Math.max(max, item.count), 0);
432
- const maxWeekdayCount = weekdayCounts.reduce((max, item) => Math.max(max, item.count), 0);
433
- const busiestDay = [...buckets]
434
- .sort((a, b) => b.totalSessions - a.totalSessions || b.totalMessages - a.totalMessages || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
435
- const busiestHour = [...hourCounts]
436
- .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
437
- const activeDays = buckets.filter((item) => item.totalSessions > 0).length;
438
- const avgMessagesPerSession = totalSessions > 0 ? Math.round((messageTotal / totalSessions) * 10) / 10 : 0;
439
- const avgSessionsPerActiveDay = activeDays > 0 ? Math.round((totalSessions / activeDays) * 10) / 10 : 0;
440
- const totalDurationMs = Number.isFinite(earliestSessionMs) && latestSessionMs > 0
441
- ? Math.max(0, latestSessionMs - earliestSessionMs)
442
- : 0;
443
-
444
- return {
445
- range,
446
- buckets,
447
- filteredSessions,
448
- summary: {
449
- totalSessions,
450
- totalMessages: messageTotal,
451
- totalTokens,
452
- totalContextWindow,
453
- activeDurationMs,
454
- totalDurationMs,
455
- codexTotal,
456
- claudeTotal,
457
- activeDays,
458
- avgMessagesPerSession,
459
- avgSessionsPerActiveDay,
460
- busiestDay: busiestDay
461
- ? {
462
- key: busiestDay.key,
463
- label: busiestDay.label,
464
- totalSessions: busiestDay.totalSessions,
465
- totalMessages: busiestDay.totalMessages
466
- }
467
- : null,
468
- busiestHour: busiestHour
469
- ? {
470
- key: busiestHour.key,
471
- label: `${busiestHour.label}:00`,
472
- count: busiestHour.count
473
- }
474
- : null
475
- },
476
- sourceShare,
477
- usedModels,
478
- modelCoverage,
479
- topPaths,
480
- recentSessions: sortedRecentSessions,
481
- topSessionsByMessages: sortedTopSessionsByMessages,
482
- hourActivity: hourCounts.map((item) => ({
483
- ...item,
484
- percent: maxHourCount > 0 ? Math.round((item.count / maxHourCount) * 100) : 0
485
- })),
486
- weekdayActivity: weekdayCounts.map((item) => ({
487
- ...item,
488
- percent: maxWeekdayCount > 0 ? Math.round((item.count / maxWeekdayCount) * 100) : 0
489
- })),
490
- maxSessionBucket,
491
- maxMessageBucket,
492
- maxHourCount,
493
- maxWeekdayCount
494
- };
495
- }
496
-
497
- export function buildSessionTimelineNodes(messages = [], options = {}) {
498
- const list = Array.isArray(messages) ? messages : [];
499
- const getKey = typeof options.getKey === 'function'
500
- ? options.getKey
501
- : ((_message, index) => `msg-${index}`);
502
- const total = list.length;
503
- const rawMaxMarkers = Number(options.maxMarkers);
504
- const maxMarkers = Number.isFinite(rawMaxMarkers)
505
- ? Math.max(1, Math.min(80, Math.floor(rawMaxMarkers)))
506
- : 30;
507
-
508
- const buildSingleNode = (message, index) => {
509
- const role = normalizeSessionMessageRole(message && (message.normalizedRole || message.role));
510
- const roleMeta = toRoleMeta(role);
511
- const key = String(getKey(message, index) || `msg-${index}`);
512
- const displayTime = formatSessionTimelineTimestamp(message && message.timestamp ? message.timestamp : '');
513
- const title = displayTime
514
- ? `#${index + 1} · ${roleMeta.roleLabel} · ${displayTime}`
515
- : `#${index + 1} · ${roleMeta.roleLabel}`;
516
- const percent = total <= 1 ? 0 : (index / (total - 1)) * 100;
517
- return {
518
- key,
519
- role: roleMeta.role,
520
- roleLabel: roleMeta.roleLabel,
521
- roleShort: roleMeta.roleShort,
522
- displayTime,
523
- title,
524
- percent,
525
- safePercent: clampTimelinePercent(percent)
526
- };
527
- };
528
-
529
- if (total <= maxMarkers) {
530
- return list.map((message, index) => buildSingleNode(message, index));
531
- }
532
-
533
- const nodes = [];
534
- const bucketWidth = total / maxMarkers;
535
- for (let bucket = 0; bucket < maxMarkers; bucket += 1) {
536
- let start = Math.floor(bucket * bucketWidth);
537
- if (nodes.length && start <= nodes[nodes.length - 1].endIndex) {
538
- start = nodes[nodes.length - 1].endIndex + 1;
539
- }
540
- if (start >= total) {
541
- break;
542
- }
543
- let end = Math.floor((bucket + 1) * bucketWidth) - 1;
544
- end = Math.max(start, Math.min(total - 1, end));
545
- const targetIndex = Math.min(total - 1, start + Math.floor((end - start) / 2));
546
- const targetMessage = list[targetIndex] || null;
547
- const key = String(getKey(targetMessage, targetIndex) || `msg-${targetIndex}`);
548
- const percent = total <= 1 ? 0 : (targetIndex / (total - 1)) * 100;
549
- const messagesInGroup = end - start + 1;
550
- const roleSet = new Set();
551
- for (let i = start; i <= end; i += 1) {
552
- roleSet.add(normalizeSessionMessageRole(list[i] && (list[i].normalizedRole || list[i].role)));
553
- }
554
- const roleValue = roleSet.size === 1 ? Array.from(roleSet)[0] : 'mixed';
555
- const roleMeta = toRoleMeta(roleValue);
556
- const firstTime = formatSessionTimelineTimestamp(list[start] && list[start].timestamp ? list[start].timestamp : '');
557
- const lastTime = formatSessionTimelineTimestamp(list[end] && list[end].timestamp ? list[end].timestamp : '');
558
- let displayTime = '';
559
- if (firstTime && lastTime) {
560
- displayTime = firstTime === lastTime ? firstTime : `${firstTime} ~ ${lastTime}`;
561
- } else {
562
- displayTime = firstTime || lastTime;
563
- }
564
- const titleBase = `#${start + 1}-${end + 1} · ${messagesInGroup} msgs · ${roleMeta.roleLabel}`;
565
- const title = displayTime ? `${titleBase} · ${displayTime}` : titleBase;
566
- nodes.push({
567
- key,
568
- role: roleMeta.role,
569
- roleLabel: roleMeta.roleLabel,
570
- roleShort: roleMeta.roleShort,
571
- displayTime,
572
- title,
573
- percent,
574
- safePercent: clampTimelinePercent(percent),
575
- startIndex: start,
576
- endIndex: end,
577
- messageCount: messagesInGroup
578
- });
579
- }
580
- return nodes;
581
- }
1
+ export const DEFAULT_SESSION_LIST_LIMIT = 200;
2
+ export const DEFAULT_SESSION_LIST_FAST_LIMIT = 20;
3
+
4
+ function shouldUseFastSessionBrowseLimit(options = {}) {
5
+ if (options.forceRefresh) {
6
+ return false;
7
+ }
8
+ const normalizedSource = normalizeSessionSource(options.source, 'all');
9
+ if (normalizedSource !== 'all') {
10
+ return false;
11
+ }
12
+ const pathFilter = normalizeSessionPathFilter(options.pathFilter);
13
+ if (pathFilter) {
14
+ return false;
15
+ }
16
+ const query = typeof options.query === 'string' ? options.query.trim() : '';
17
+ if (query) {
18
+ return false;
19
+ }
20
+ const roleFilter = typeof options.roleFilter === 'string' ? options.roleFilter.trim().toLowerCase() : 'all';
21
+ if (roleFilter && roleFilter !== 'all') {
22
+ return false;
23
+ }
24
+ const timeRangePreset = typeof options.timeRangePreset === 'string'
25
+ ? options.timeRangePreset.trim().toLowerCase()
26
+ : 'all';
27
+ return !timeRangePreset || timeRangePreset === 'all';
28
+ }
29
+
30
+ export function isSessionQueryEnabled(source) {
31
+ const normalized = normalizeSessionSource(source, '');
32
+ return normalized === 'codex' || normalized === 'claude' || normalized === 'all';
33
+ }
34
+
35
+ export function normalizeSessionSource(source, fallback = 'all') {
36
+ const normalized = typeof source === 'string'
37
+ ? source.trim().toLowerCase()
38
+ : '';
39
+ if (normalized === 'codex' || normalized === 'claude' || normalized === 'all') {
40
+ return normalized;
41
+ }
42
+ return fallback;
43
+ }
44
+
45
+ export function normalizeSessionPathFilter(pathFilter) {
46
+ return typeof pathFilter === 'string' ? pathFilter.trim() : '';
47
+ }
48
+
49
+ function isConcreteSessionModelName(value) {
50
+ if (typeof value !== 'string') {
51
+ return false;
52
+ }
53
+ const normalized = value.trim();
54
+ if (!normalized) {
55
+ return false;
56
+ }
57
+ return normalized.toLowerCase() !== '<synthetic>';
58
+ }
59
+
60
+ function collectSessionModelNames(session) {
61
+ if (!session || typeof session !== 'object') {
62
+ return [];
63
+ }
64
+ const values = Array.isArray(session.models)
65
+ ? [...session.models, session.model, session.modelName, session.modelId]
66
+ : [session.model, session.modelName, session.modelId];
67
+ const models = [];
68
+ for (const value of values) {
69
+ if (!isConcreteSessionModelName(value)) {
70
+ continue;
71
+ }
72
+ const normalized = value.trim();
73
+ if (models.includes(normalized)) {
74
+ continue;
75
+ }
76
+ models.push(normalized);
77
+ }
78
+ return models;
79
+ }
80
+
81
+ function readSessionTotalTokens(session) {
82
+ if (!session || typeof session !== 'object') {
83
+ return 0;
84
+ }
85
+
86
+ const rawTotalTokens = Number(session.totalTokens);
87
+ const hasExplicitTotal = Number.isFinite(rawTotalTokens) && rawTotalTokens >= 0;
88
+ const explicitTotal = hasExplicitTotal ? Math.max(0, Math.floor(rawTotalTokens)) : null;
89
+
90
+ const inputTokens = Number.isFinite(Number(session.inputTokens))
91
+ ? Math.max(0, Math.floor(Number(session.inputTokens)))
92
+ : null;
93
+ const outputTokens = Number.isFinite(Number(session.outputTokens))
94
+ ? Math.max(0, Math.floor(Number(session.outputTokens)))
95
+ : null;
96
+ const reasoningOutputTokens = Number.isFinite(Number(session.reasoningOutputTokens))
97
+ ? Math.max(0, Math.floor(Number(session.reasoningOutputTokens)))
98
+ : 0;
99
+
100
+ // 对齐 usage 口径:当总 token 缺失时,使用拆分字段回填(input + output + reasoning)。
101
+ // cachedInputTokens 一般包含在 inputTokens 中,因此不在此重复相加。
102
+ const hasBreakdown = !(inputTokens === null && outputTokens === null && reasoningOutputTokens === 0);
103
+ const breakdownTotal = hasBreakdown
104
+ ? (inputTokens || 0) + (outputTokens || 0) + reasoningOutputTokens
105
+ : 0;
106
+
107
+ if (breakdownTotal > 0) {
108
+ return breakdownTotal;
109
+ }
110
+ if (explicitTotal !== null) {
111
+ return explicitTotal;
112
+ }
113
+ return 0;
114
+ }
115
+
116
+ export function buildSessionFilterCacheState(source, pathFilter) {
117
+ return {
118
+ source: normalizeSessionSource(source, 'all'),
119
+ pathFilter: normalizeSessionPathFilter(pathFilter)
120
+ };
121
+ }
122
+
123
+ export function buildSessionListParams(options = {}) {
124
+ const fallbackLimit = shouldUseFastSessionBrowseLimit(options)
125
+ ? DEFAULT_SESSION_LIST_FAST_LIMIT
126
+ : DEFAULT_SESSION_LIST_LIMIT;
127
+ const {
128
+ source = 'all',
129
+ pathFilter = '',
130
+ query = '',
131
+ roleFilter = 'all',
132
+ timeRangePreset = 'all',
133
+ limit = fallbackLimit,
134
+ forceRefresh = false
135
+ } = options;
136
+ const normalizedSource = normalizeSessionSource(source, 'all');
137
+ const normalizedPathFilter = normalizeSessionPathFilter(pathFilter);
138
+ const queryValue = isSessionQueryEnabled(normalizedSource) ? query : '';
139
+ return {
140
+ source: normalizedSource,
141
+ pathFilter: normalizedPathFilter,
142
+ query: queryValue,
143
+ queryMode: 'and',
144
+ queryScope: 'content',
145
+ contentScanLimit: 50,
146
+ roleFilter,
147
+ timeRangePreset,
148
+ limit,
149
+ forceRefresh: !!forceRefresh
150
+ };
151
+ }
152
+
153
+ export function normalizeSessionMessageRole(role) {
154
+ const value = typeof role === 'string' ? role.trim().toLowerCase() : '';
155
+ if (value === 'user' || value === 'assistant' || value === 'system') {
156
+ return value;
157
+ }
158
+ return 'assistant';
159
+ }
160
+
161
+ function toRoleMeta(role) {
162
+ if (role === 'user') {
163
+ return { role: 'user', roleLabel: 'User', roleShort: 'U' };
164
+ }
165
+ if (role === 'assistant') {
166
+ return { role: 'assistant', roleLabel: 'Assistant', roleShort: 'A' };
167
+ }
168
+ if (role === 'system') {
169
+ return { role: 'system', roleLabel: 'System', roleShort: 'S' };
170
+ }
171
+ return { role: 'mixed', roleLabel: 'Mixed', roleShort: 'M' };
172
+ }
173
+
174
+ function clampTimelinePercent(percent) {
175
+ return Math.max(6, Math.min(94, percent));
176
+ }
177
+
178
+ export function formatSessionTimelineTimestamp(timestamp) {
179
+ const value = typeof timestamp === 'string' ? timestamp.trim() : '';
180
+ if (!value) return '';
181
+
182
+ const matched = value.match(/^(\d{4})-(\d{2})-(\d{2})[T\s](\d{2}):(\d{2})(?::(\d{2}))?/);
183
+ if (matched) {
184
+ const second = matched[6] || '00';
185
+ return `${matched[2]}-${matched[3]} ${matched[4]}:${matched[5]}:${second}`;
186
+ }
187
+
188
+ return value;
189
+ }
190
+
191
+ function normalizeUsageRange(range) {
192
+ const normalized = typeof range === 'string' ? range.trim().toLowerCase() : '7d';
193
+ if (normalized === '30d' || normalized === 'all') {
194
+ return normalized;
195
+ }
196
+ return '7d';
197
+ }
198
+
199
+ function toUtcDayStartMs(value) {
200
+ const stamp = new Date(value);
201
+ return Date.UTC(stamp.getUTCFullYear(), stamp.getUTCMonth(), stamp.getUTCDate());
202
+ }
203
+
204
+ function formatUtcDayKey(value) {
205
+ const stamp = new Date(value);
206
+ return `${stamp.getUTCFullYear()}-${String(stamp.getUTCMonth() + 1).padStart(2, '0')}-${String(stamp.getUTCDate()).padStart(2, '0')}`;
207
+ }
208
+
209
+ function buildUsageBuckets(normalizedSessions, options = {}) {
210
+ const range = normalizeUsageRange(options.range);
211
+ const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
212
+ const dayMs = 24 * 60 * 60 * 1000;
213
+ const buckets = [];
214
+
215
+ if (range === 'all') {
216
+ const validDayStarts = normalizedSessions
217
+ .map((session) => toUtcDayStartMs(session.updatedAtMs))
218
+ .filter((value) => Number.isFinite(value));
219
+ const firstDayStart = validDayStarts.length ? Math.min(...validDayStarts) : toUtcDayStartMs(now);
220
+ const lastDayStart = validDayStarts.length ? Math.max(...validDayStarts) : toUtcDayStartMs(now);
221
+ for (let stamp = firstDayStart; stamp <= lastDayStart; stamp += dayMs) {
222
+ const key = formatUtcDayKey(stamp);
223
+ buckets.push({
224
+ key,
225
+ label: key.slice(5),
226
+ codex: 0,
227
+ claude: 0,
228
+ totalMessages: 0,
229
+ totalSessions: 0
230
+ });
231
+ }
232
+ return { range, buckets };
233
+ }
234
+
235
+ const rangeDays = range === '30d' ? 30 : 7;
236
+ for (let i = rangeDays - 1; i >= 0; i -= 1) {
237
+ const stamp = new Date(now - (i * dayMs));
238
+ const key = formatUtcDayKey(stamp);
239
+ buckets.push({
240
+ key,
241
+ label: key.slice(5),
242
+ codex: 0,
243
+ claude: 0,
244
+ totalMessages: 0,
245
+ totalSessions: 0
246
+ });
247
+ }
248
+ return { range, buckets };
249
+ }
250
+
251
+ export function buildUsageChartGroups(sessions = [], options = {}) {
252
+ const list = Array.isArray(sessions) ? sessions : [];
253
+ const normalizedSessions = [];
254
+ for (const [sessionIndex, session] of list.entries()) {
255
+ if (!session || typeof session !== 'object') continue;
256
+ const source = normalizeSessionSource(session.source, '');
257
+ if (source !== 'codex' && source !== 'claude') continue;
258
+ const updatedAtMs = Date.parse(session.updatedAt || '');
259
+ if (!Number.isFinite(updatedAtMs)) continue;
260
+ const createdAtMs = Date.parse(session.createdAt || '');
261
+ const sessionStartedAtMs = Number.isFinite(createdAtMs) ? createdAtMs : updatedAtMs;
262
+ const sessionEndedAtMs = Math.max(updatedAtMs, sessionStartedAtMs);
263
+ normalizedSessions.push({
264
+ session,
265
+ sessionIndex,
266
+ source,
267
+ updatedAtMs,
268
+ createdAtMs,
269
+ sessionStartedAtMs,
270
+ sessionEndedAtMs,
271
+ bucketKey: formatUtcDayKey(updatedAtMs)
272
+ });
273
+ }
274
+ const { range, buckets } = buildUsageBuckets(normalizedSessions, options);
275
+ const bucketMap = new Map(buckets.map((bucket) => [bucket.key, bucket]));
276
+ let codexTotal = 0;
277
+ let claudeTotal = 0;
278
+ let messageTotal = 0;
279
+ let totalTokens = 0;
280
+ let totalContextWindow = 0;
281
+ let activeDurationMs = 0;
282
+ let earliestSessionMs = Number.POSITIVE_INFINITY;
283
+ let latestSessionMs = 0;
284
+ const pathMap = new Map();
285
+ const modelMap = new Map();
286
+ const missingModelProviderMap = new Map();
287
+ const missingModelSessionMap = new Map();
288
+ const sourceMessageTotals = { codex: 0, claude: 0 };
289
+ const missingModelSourceTotals = { codex: 0, claude: 0 };
290
+ let missingModelSessions = 0;
291
+ let providerOnlySessions = 0;
292
+ const hourCounts = Array.from({ length: 24 }, (_, hour) => ({
293
+ key: String(hour).padStart(2, '0'),
294
+ label: String(hour).padStart(2, '0'),
295
+ count: 0
296
+ }));
297
+ const weekdayLabels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
298
+ const weekdayCounts = Array.from({ length: 7 }, (_, index) => ({
299
+ key: String(index),
300
+ label: weekdayLabels[index],
301
+ count: 0
302
+ }));
303
+ const recentSessions = [];
304
+ const topSessionsByMessages = [];
305
+ const filteredSessions = [];
306
+
307
+ for (const normalized of normalizedSessions) {
308
+ const { session, sessionIndex, source, updatedAtMs, sessionStartedAtMs, sessionEndedAtMs, bucketKey } = normalized;
309
+ const stamp = new Date(updatedAtMs);
310
+ const bucket = bucketMap.get(bucketKey);
311
+ if (!bucket) continue;
312
+ const sessionModels = collectSessionModelNames(session);
313
+ if (sessionModels.length === 0) continue;
314
+ filteredSessions.push(session);
315
+ const messageCount = Number.isFinite(Number(session.messageCount))
316
+ ? Math.max(0, Math.floor(Number(session.messageCount)))
317
+ : 0;
318
+ const sessionTotalTokens = readSessionTotalTokens(session);
319
+ const sessionContextWindow = Number.isFinite(Number(session.contextWindow))
320
+ ? Math.max(0, Math.floor(Number(session.contextWindow)))
321
+ : 0;
322
+ bucket.totalSessions += 1;
323
+ bucket.totalMessages += messageCount;
324
+ if (source === 'codex') {
325
+ bucket.codex += 1;
326
+ codexTotal += 1;
327
+ } else {
328
+ bucket.claude += 1;
329
+ claudeTotal += 1;
330
+ }
331
+ messageTotal += messageCount;
332
+ totalTokens += sessionTotalTokens;
333
+ totalContextWindow += sessionContextWindow;
334
+ sourceMessageTotals[source] += messageCount;
335
+ activeDurationMs += Math.max(0, sessionEndedAtMs - sessionStartedAtMs);
336
+ earliestSessionMs = Math.min(earliestSessionMs, sessionStartedAtMs);
337
+ latestSessionMs = Math.max(latestSessionMs, sessionEndedAtMs);
338
+
339
+ const utcHour = stamp.getUTCHours();
340
+ if (hourCounts[utcHour]) {
341
+ hourCounts[utcHour].count += 1;
342
+ }
343
+ const dayIndex = (stamp.getUTCDay() + 6) % 7;
344
+ if (weekdayCounts[dayIndex]) {
345
+ weekdayCounts[dayIndex].count += 1;
346
+ }
347
+
348
+ const cwd = normalizeSessionPathFilter(session.cwd);
349
+ if (cwd) {
350
+ const prev = pathMap.get(cwd) || { count: 0, messageTotal: 0, updatedAtMs: 0 };
351
+ pathMap.set(cwd, {
352
+ count: prev.count + 1,
353
+ messageTotal: prev.messageTotal + messageCount,
354
+ updatedAtMs: Math.max(prev.updatedAtMs, updatedAtMs)
355
+ });
356
+ }
357
+
358
+ const sourceLabel = source === 'codex' ? 'Codex' : 'Claude Code';
359
+ const normalizedTitle = typeof session.title === 'string' && session.title.trim()
360
+ ? session.title.trim()
361
+ : (typeof session.sessionId === 'string' && session.sessionId.trim() ? session.sessionId.trim() : '未命名会话');
362
+ for (const modelId of sessionModels) {
363
+ const prev = modelMap.get(modelId) || {
364
+ count: 0,
365
+ messageTotal: 0,
366
+ tokenTotal: 0,
367
+ sources: new Set()
368
+ };
369
+ prev.count += 1;
370
+ prev.messageTotal += messageCount;
371
+ prev.tokenTotal += sessionTotalTokens;
372
+ prev.sources.add(source);
373
+ modelMap.set(modelId, prev);
374
+ }
375
+
376
+ const sessionEntry = {
377
+ key: [
378
+ source,
379
+ session.sessionId || '',
380
+ session.filePath || normalizedTitle,
381
+ String(updatedAtMs),
382
+ String(messageCount),
383
+ String(sessionIndex)
384
+ ].join(':'),
385
+ title: normalizedTitle,
386
+ source,
387
+ sourceLabel,
388
+ cwd,
389
+ messageCount,
390
+ updatedAt: session.updatedAt || '',
391
+ updatedAtMs,
392
+ updatedAtLabel: formatSessionTimelineTimestamp(session.updatedAt || ''),
393
+ hasExactMessageCount: session.__messageCountExact === true
394
+ };
395
+ recentSessions.push(sessionEntry);
396
+ topSessionsByMessages.push({ ...sessionEntry });
397
+ }
398
+
399
+ const totalSessions = codexTotal + claudeTotal;
400
+ const sourceShare = [
401
+ { key: 'codex', label: 'Codex', value: codexTotal },
402
+ { key: 'claude', label: 'Claude', value: claudeTotal }
403
+ ].map((item) => ({
404
+ ...item,
405
+ percent: totalSessions > 0 ? Math.round((item.value / totalSessions) * 100) : 0,
406
+ messageTotal: sourceMessageTotals[item.key] || 0,
407
+ messagePercent: messageTotal > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / messageTotal) * 100) : 0,
408
+ avgMessages: item.value > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / item.value) * 10) / 10 : 0
409
+ }));
410
+
411
+ const topPaths = [...pathMap.entries()]
412
+ .sort((a, b) => b[1].count - a[1].count || b[1].messageTotal - a[1].messageTotal || a[0].localeCompare(b[0], 'zh-Hans-CN'))
413
+ .slice(0, 5)
414
+ .map(([pathValue, meta]) => ({
415
+ path: pathValue,
416
+ count: meta.count,
417
+ messageTotal: meta.messageTotal,
418
+ updatedAtLabel: meta.updatedAtMs ? formatSessionTimelineTimestamp(new Date(meta.updatedAtMs).toISOString()) : ''
419
+ }));
420
+
421
+ const usedModels = [...modelMap.entries()]
422
+ .sort((a, b) => b[1].count - a[1].count)
423
+ .map(([modelId, meta]) => {
424
+ const sourceLabels = [...meta.sources]
425
+ .sort((a, b) => a.localeCompare(b, 'en-US'))
426
+ .map((source) => (source === 'codex' ? 'Codex' : 'Claude Code'));
427
+ return {
428
+ key: modelId,
429
+ model: modelId,
430
+ count: meta.count,
431
+ messageTotal: meta.messageTotal,
432
+ tokenTotal: meta.tokenTotal,
433
+ sourceLabels
434
+ };
435
+ });
436
+
437
+ const sortedRecentSessions = recentSessions
438
+ .sort((a, b) => b.updatedAtMs - a.updatedAtMs || b.messageCount - a.messageCount || a.title.localeCompare(b.title, 'zh-Hans-CN'))
439
+ .slice(0, 6);
440
+
441
+ const missingModelProviders = [...missingModelProviderMap.values()]
442
+ .sort((a, b) => b.count - a.count || a.label.localeCompare(b.label, 'zh-Hans-CN'));
443
+ const missingModelSessionsPreview = [...missingModelSessionMap.values()]
444
+ .sort((a, b) => b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
445
+ .slice(0, 5);
446
+
447
+ const modelCoverage = {
448
+ totalSessions,
449
+ modeledSessions: Math.max(0, totalSessions - missingModelSessions),
450
+ missingModelSessions,
451
+ providerOnlySessions,
452
+ missingModelSourceTotals,
453
+ missingModelProviders,
454
+ missingModelSessionsPreview,
455
+ coveragePercent: totalSessions > 0 ? Math.round(((totalSessions - missingModelSessions) / totalSessions) * 100) : 0
456
+ };
457
+
458
+ const sortedTopSessionsByMessages = topSessionsByMessages
459
+ .sort((a, b) => b.messageCount - a.messageCount || b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
460
+ .slice(0, 6);
461
+
462
+ const maxSessionBucket = buckets.reduce((max, item) => Math.max(max, item.totalSessions), 0);
463
+ const maxMessageBucket = buckets.reduce((max, item) => Math.max(max, item.totalMessages), 0);
464
+ const maxHourCount = hourCounts.reduce((max, item) => Math.max(max, item.count), 0);
465
+ const maxWeekdayCount = weekdayCounts.reduce((max, item) => Math.max(max, item.count), 0);
466
+ const busiestDay = [...buckets]
467
+ .sort((a, b) => b.totalSessions - a.totalSessions || b.totalMessages - a.totalMessages || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
468
+ const busiestHour = [...hourCounts]
469
+ .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
470
+ const activeDays = buckets.filter((item) => item.totalSessions > 0).length;
471
+ const avgMessagesPerSession = totalSessions > 0 ? Math.round((messageTotal / totalSessions) * 10) / 10 : 0;
472
+ const avgSessionsPerActiveDay = activeDays > 0 ? Math.round((totalSessions / activeDays) * 10) / 10 : 0;
473
+ const totalDurationMs = Number.isFinite(earliestSessionMs) && latestSessionMs > 0
474
+ ? Math.max(0, latestSessionMs - earliestSessionMs)
475
+ : 0;
476
+
477
+ return {
478
+ range,
479
+ buckets,
480
+ filteredSessions,
481
+ summary: {
482
+ totalSessions,
483
+ totalMessages: messageTotal,
484
+ totalTokens,
485
+ totalContextWindow,
486
+ activeDurationMs,
487
+ totalDurationMs,
488
+ codexTotal,
489
+ claudeTotal,
490
+ activeDays,
491
+ avgMessagesPerSession,
492
+ avgSessionsPerActiveDay,
493
+ busiestDay: busiestDay
494
+ ? {
495
+ key: busiestDay.key,
496
+ label: busiestDay.label,
497
+ totalSessions: busiestDay.totalSessions,
498
+ totalMessages: busiestDay.totalMessages
499
+ }
500
+ : null,
501
+ busiestHour: busiestHour
502
+ ? {
503
+ key: busiestHour.key,
504
+ label: `${busiestHour.label}:00`,
505
+ count: busiestHour.count
506
+ }
507
+ : null
508
+ },
509
+ sourceShare,
510
+ usedModels,
511
+ modelCoverage,
512
+ topPaths,
513
+ recentSessions: sortedRecentSessions,
514
+ topSessionsByMessages: sortedTopSessionsByMessages,
515
+ hourActivity: hourCounts.map((item) => ({
516
+ ...item,
517
+ percent: maxHourCount > 0 ? Math.round((item.count / maxHourCount) * 100) : 0
518
+ })),
519
+ weekdayActivity: weekdayCounts.map((item) => ({
520
+ ...item,
521
+ percent: maxWeekdayCount > 0 ? Math.round((item.count / maxWeekdayCount) * 100) : 0
522
+ })),
523
+ maxSessionBucket,
524
+ maxMessageBucket,
525
+ maxHourCount,
526
+ maxWeekdayCount
527
+ };
528
+ }
529
+
530
+ export function buildSessionTimelineNodes(messages = [], options = {}) {
531
+ const list = Array.isArray(messages) ? messages : [];
532
+ const getKey = typeof options.getKey === 'function'
533
+ ? options.getKey
534
+ : ((_message, index) => `msg-${index}`);
535
+ const total = list.length;
536
+ const rawMaxMarkers = Number(options.maxMarkers);
537
+ const maxMarkers = Number.isFinite(rawMaxMarkers)
538
+ ? Math.max(1, Math.min(80, Math.floor(rawMaxMarkers)))
539
+ : 30;
540
+
541
+ const buildSingleNode = (message, index) => {
542
+ const role = normalizeSessionMessageRole(message && (message.normalizedRole || message.role));
543
+ const roleMeta = toRoleMeta(role);
544
+ const key = String(getKey(message, index) || `msg-${index}`);
545
+ const displayTime = formatSessionTimelineTimestamp(message && message.timestamp ? message.timestamp : '');
546
+ const title = displayTime
547
+ ? `#${index + 1} · ${roleMeta.roleLabel} · ${displayTime}`
548
+ : `#${index + 1} · ${roleMeta.roleLabel}`;
549
+ const percent = total <= 1 ? 0 : (index / (total - 1)) * 100;
550
+ return {
551
+ key,
552
+ role: roleMeta.role,
553
+ roleLabel: roleMeta.roleLabel,
554
+ roleShort: roleMeta.roleShort,
555
+ displayTime,
556
+ title,
557
+ percent,
558
+ safePercent: clampTimelinePercent(percent)
559
+ };
560
+ };
561
+
562
+ if (total <= maxMarkers) {
563
+ return list.map((message, index) => buildSingleNode(message, index));
564
+ }
565
+
566
+ const nodes = [];
567
+ const bucketWidth = total / maxMarkers;
568
+ for (let bucket = 0; bucket < maxMarkers; bucket += 1) {
569
+ let start = Math.floor(bucket * bucketWidth);
570
+ if (nodes.length && start <= nodes[nodes.length - 1].endIndex) {
571
+ start = nodes[nodes.length - 1].endIndex + 1;
572
+ }
573
+ if (start >= total) {
574
+ break;
575
+ }
576
+ let end = Math.floor((bucket + 1) * bucketWidth) - 1;
577
+ end = Math.max(start, Math.min(total - 1, end));
578
+ const targetIndex = Math.min(total - 1, start + Math.floor((end - start) / 2));
579
+ const targetMessage = list[targetIndex] || null;
580
+ const key = String(getKey(targetMessage, targetIndex) || `msg-${targetIndex}`);
581
+ const percent = total <= 1 ? 0 : (targetIndex / (total - 1)) * 100;
582
+ const messagesInGroup = end - start + 1;
583
+ const roleSet = new Set();
584
+ for (let i = start; i <= end; i += 1) {
585
+ roleSet.add(normalizeSessionMessageRole(list[i] && (list[i].normalizedRole || list[i].role)));
586
+ }
587
+ const roleValue = roleSet.size === 1 ? Array.from(roleSet)[0] : 'mixed';
588
+ const roleMeta = toRoleMeta(roleValue);
589
+ const firstTime = formatSessionTimelineTimestamp(list[start] && list[start].timestamp ? list[start].timestamp : '');
590
+ const lastTime = formatSessionTimelineTimestamp(list[end] && list[end].timestamp ? list[end].timestamp : '');
591
+ let displayTime = '';
592
+ if (firstTime && lastTime) {
593
+ displayTime = firstTime === lastTime ? firstTime : `${firstTime} ~ ${lastTime}`;
594
+ } else {
595
+ displayTime = firstTime || lastTime;
596
+ }
597
+ const titleBase = `#${start + 1}-${end + 1} · ${messagesInGroup} msgs · ${roleMeta.roleLabel}`;
598
+ const title = displayTime ? `${titleBase} · ${displayTime}` : titleBase;
599
+ nodes.push({
600
+ key,
601
+ role: roleMeta.role,
602
+ roleLabel: roleMeta.roleLabel,
603
+ roleShort: roleMeta.roleShort,
604
+ displayTime,
605
+ title,
606
+ percent,
607
+ safePercent: clampTimelinePercent(percent),
608
+ startIndex: start,
609
+ endIndex: end,
610
+ messageCount: messagesInGroup
611
+ });
612
+ }
613
+ return nodes;
614
+ }