codexmate 0.0.26 → 0.0.27

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 (135) hide show
  1. package/README.md +421 -416
  2. package/README.zh.md +354 -349
  3. package/cli/agents-files.js +224 -224
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +375 -375
  6. package/cli/builtin-proxy.js +1299 -1079
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +384 -384
  9. package/cli/config-health.js +338 -338
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/openai-bridge.js +1091 -997
  13. package/cli/openclaw-config.js +629 -629
  14. package/cli/session-convert-args.js +65 -65
  15. package/cli/session-convert-io.js +82 -82
  16. package/cli/session-convert.js +43 -43
  17. package/cli/session-usage.concurrent.js +28 -28
  18. package/cli/session-usage.js +118 -118
  19. package/cli/session-usage.models.js +176 -176
  20. package/cli/skills.js +1141 -1141
  21. package/cli/zip-commands.js +510 -510
  22. package/cli.js +15251 -15218
  23. package/lib/automation.js +404 -404
  24. package/lib/cli-file-utils.js +151 -151
  25. package/lib/cli-models-utils.js +379 -379
  26. package/lib/cli-network-utils.js +190 -190
  27. package/lib/cli-path-utils.js +85 -85
  28. package/lib/cli-session-utils.js +121 -121
  29. package/lib/cli-sessions.js +417 -417
  30. package/lib/cli-utils.js +155 -155
  31. package/lib/download-artifacts.js +92 -92
  32. package/lib/mcp-stdio.js +453 -453
  33. package/lib/task-orchestrator.js +869 -869
  34. package/lib/text-diff.js +303 -303
  35. package/lib/workflow-engine.js +340 -340
  36. package/package.json +1 -1
  37. package/plugins/README.md +20 -20
  38. package/plugins/README.zh-CN.md +20 -20
  39. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  40. package/plugins/prompt-templates/computed.mjs +253 -253
  41. package/plugins/prompt-templates/index.mjs +8 -8
  42. package/plugins/prompt-templates/manifest.mjs +15 -15
  43. package/plugins/prompt-templates/methods.mjs +619 -619
  44. package/plugins/prompt-templates/overview.mjs +90 -90
  45. package/plugins/prompt-templates/ownership.mjs +19 -19
  46. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  47. package/plugins/prompt-templates/storage.mjs +64 -64
  48. package/plugins/registry.mjs +16 -16
  49. package/web-ui/app.js +634 -625
  50. package/web-ui/index.html +35 -35
  51. package/web-ui/logic.agents-diff.mjs +386 -386
  52. package/web-ui/logic.claude.mjs +168 -168
  53. package/web-ui/logic.mjs +5 -5
  54. package/web-ui/logic.runtime.mjs +128 -128
  55. package/web-ui/logic.session-convert.mjs +70 -70
  56. package/web-ui/logic.sessions.mjs +765 -709
  57. package/web-ui/modules/api.mjs +90 -90
  58. package/web-ui/modules/app.computed.dashboard.mjs +171 -171
  59. package/web-ui/modules/app.computed.index.mjs +17 -17
  60. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  61. package/web-ui/modules/app.computed.session.mjs +994 -946
  62. package/web-ui/modules/app.constants.mjs +15 -15
  63. package/web-ui/modules/app.methods.agents.mjs +632 -632
  64. package/web-ui/modules/app.methods.claude-config.mjs +184 -179
  65. package/web-ui/modules/app.methods.codex-config.mjs +860 -860
  66. package/web-ui/modules/app.methods.index.mjs +92 -92
  67. package/web-ui/modules/app.methods.install.mjs +205 -205
  68. package/web-ui/modules/app.methods.navigation.mjs +743 -743
  69. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  70. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  71. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  72. package/web-ui/modules/app.methods.providers.mjs +404 -404
  73. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  74. package/web-ui/modules/app.methods.session-actions.mjs +596 -596
  75. package/web-ui/modules/app.methods.session-browser.mjs +989 -985
  76. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  77. package/web-ui/modules/app.methods.session-trash.mjs +439 -424
  78. package/web-ui/modules/app.methods.startup-claude.mjs +526 -522
  79. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  80. package/web-ui/modules/config-mode.computed.mjs +124 -124
  81. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  82. package/web-ui/modules/i18n.dict.mjs +2131 -2113
  83. package/web-ui/modules/i18n.mjs +56 -56
  84. package/web-ui/modules/plugins.computed.mjs +3 -3
  85. package/web-ui/modules/plugins.methods.mjs +3 -3
  86. package/web-ui/modules/plugins.storage.mjs +11 -11
  87. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  88. package/web-ui/modules/skills.computed.mjs +107 -107
  89. package/web-ui/modules/skills.methods.mjs +481 -481
  90. package/web-ui/partials/index/layout-footer.html +13 -13
  91. package/web-ui/partials/index/layout-header.html +475 -475
  92. package/web-ui/partials/index/modal-config-template-agents.html +174 -174
  93. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  94. package/web-ui/partials/index/modal-health-check.html +45 -45
  95. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  96. package/web-ui/partials/index/modal-skills.html +200 -200
  97. package/web-ui/partials/index/modals-basic.html +165 -165
  98. package/web-ui/partials/index/panel-config-claude.html +187 -184
  99. package/web-ui/partials/index/panel-config-codex.html +283 -283
  100. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  101. package/web-ui/partials/index/panel-dashboard.html +186 -186
  102. package/web-ui/partials/index/panel-docs.html +147 -147
  103. package/web-ui/partials/index/panel-market.html +177 -177
  104. package/web-ui/partials/index/panel-orchestration.html +391 -391
  105. package/web-ui/partials/index/panel-plugins.html +279 -279
  106. package/web-ui/partials/index/panel-sessions.html +326 -326
  107. package/web-ui/partials/index/panel-settings.html +274 -258
  108. package/web-ui/partials/index/panel-usage.html +371 -342
  109. package/web-ui/res/json5.min.js +1 -1
  110. package/web-ui/res/vue.global.prod.js +13 -13
  111. package/web-ui/session-helpers.mjs +576 -576
  112. package/web-ui/source-bundle.cjs +233 -233
  113. package/web-ui/styles/base-theme.css +268 -268
  114. package/web-ui/styles/controls-forms.css +423 -423
  115. package/web-ui/styles/dashboard.css +274 -274
  116. package/web-ui/styles/docs-panel.css +247 -247
  117. package/web-ui/styles/feedback.css +108 -108
  118. package/web-ui/styles/health-check-dialog.css +144 -144
  119. package/web-ui/styles/layout-shell.css +603 -603
  120. package/web-ui/styles/modals-core.css +464 -464
  121. package/web-ui/styles/navigation-panels.css +390 -390
  122. package/web-ui/styles/openclaw-structured.css +266 -266
  123. package/web-ui/styles/plugins-panel.css +523 -523
  124. package/web-ui/styles/responsive.css +454 -454
  125. package/web-ui/styles/sessions-list.css +415 -415
  126. package/web-ui/styles/sessions-preview.css +411 -411
  127. package/web-ui/styles/sessions-toolbar-trash.css +330 -330
  128. package/web-ui/styles/sessions-usage.css +1040 -945
  129. package/web-ui/styles/settings-panel.css +185 -166
  130. package/web-ui/styles/skills-list.css +303 -303
  131. package/web-ui/styles/skills-market.css +406 -406
  132. package/web-ui/styles/task-orchestration.css +822 -822
  133. package/web-ui/styles/titles-cards.css +408 -408
  134. package/web-ui/styles.css +21 -21
  135. package/web-ui.html +17 -17
@@ -1,709 +1,765 @@
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 === 'gemini' || normalized === 'codebuddy' || 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 === 'gemini' || normalized === 'codebuddy' || 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
- export function buildUsageHeatmap(sessions = [], options = {}) {
210
- const list = Array.isArray(sessions) ? sessions : [];
211
- const normalized = [];
212
- for (const session of list) {
213
- if (!session || typeof session !== 'object') continue;
214
- const source = normalizeSessionSource(session.source, '');
215
- if (source !== 'codex' && source !== 'claude') continue;
216
- const updatedAtMs = Date.parse(session.updatedAt || '');
217
- if (!Number.isFinite(updatedAtMs)) continue;
218
- normalized.push({
219
- updatedAtMs,
220
- messageCount: Number.isFinite(Number(session.messageCount))
221
- ? Math.max(0, Math.floor(Number(session.messageCount)))
222
- : 0,
223
- tokenTotal: readSessionTotalTokens(session)
224
- });
225
- }
226
-
227
- const range = normalizeUsageRange(options.range);
228
- const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
229
- const dayMs = 24 * 60 * 60 * 1000;
230
- const todayStart = toUtcDayStartMs(now);
231
- let startDay = todayStart;
232
- let endDay = todayStart;
233
- if (range === 'all') {
234
- const dayStarts = normalized.map((item) => toUtcDayStartMs(item.updatedAtMs)).filter((value) => Number.isFinite(value));
235
- if (dayStarts.length) {
236
- startDay = Math.min(...dayStarts);
237
- endDay = Math.max(...dayStarts);
238
- }
239
- } else {
240
- const rangeDays = range === '30d' ? 30 : 7;
241
- endDay = todayStart;
242
- startDay = todayStart - ((rangeDays - 1) * dayMs);
243
- }
244
-
245
- const startDow = new Date(startDay).getUTCDay();
246
- const startShift = (startDow + 6) % 7;
247
- const alignedStart = startDay - (startShift * dayMs);
248
- const endDow = new Date(endDay).getUTCDay();
249
- const endShift = (6 - ((endDow + 6) % 7));
250
- const alignedEnd = endDay + (endShift * dayMs);
251
- const totalDays = Math.floor((alignedEnd - alignedStart) / dayMs) + 1;
252
- const weekCount = Math.max(1, Math.ceil(totalDays / 7));
253
-
254
- const byDay = new Map();
255
- for (const item of normalized) {
256
- const dayKey = formatUtcDayKey(item.updatedAtMs);
257
- const existing = byDay.get(dayKey) || { sessionCount: 0, messageCount: 0, tokenTotal: 0 };
258
- existing.sessionCount += 1;
259
- existing.messageCount += item.messageCount;
260
- existing.tokenTotal += item.tokenTotal;
261
- byDay.set(dayKey, existing);
262
- }
263
-
264
- const weeks = Array.from({ length: weekCount }, (_, idx) => ({
265
- key: `w-${idx}`,
266
- weekIndex: idx,
267
- days: Array.from({ length: 7 }, () => null)
268
- }));
269
-
270
- let maxSessionCount = 0;
271
- for (let dayIndex = 0; dayIndex < totalDays; dayIndex += 1) {
272
- const dateMs = alignedStart + (dayIndex * dayMs);
273
- const dateKey = formatUtcDayKey(dateMs);
274
- const isInRange = dateMs >= startDay && dateMs <= endDay;
275
- const weekIndex = Math.floor(dayIndex / 7);
276
- const dow = new Date(dateMs).getUTCDay();
277
- const rowIndex = (dow + 6) % 7;
278
- const totals = isInRange ? (byDay.get(dateKey) || { sessionCount: 0, messageCount: 0, tokenTotal: 0 }) : null;
279
- const sessionCount = totals ? totals.sessionCount : 0;
280
- if (isInRange) {
281
- maxSessionCount = Math.max(maxSessionCount, sessionCount);
282
- }
283
- weeks[weekIndex].days[rowIndex] = {
284
- dateKey,
285
- dateMs,
286
- isInRange,
287
- sessionCount,
288
- messageCount: totals ? totals.messageCount : 0,
289
- tokenTotal: totals ? totals.tokenTotal : 0
290
- };
291
- }
292
-
293
- return {
294
- range,
295
- startDay,
296
- endDay,
297
- alignedStart,
298
- alignedEnd,
299
- maxSessionCount,
300
- weeks
301
- };
302
- }
303
-
304
- function buildUsageBuckets(normalizedSessions, options = {}) {
305
- const range = normalizeUsageRange(options.range);
306
- const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
307
- const dayMs = 24 * 60 * 60 * 1000;
308
- const buckets = [];
309
-
310
- if (range === 'all') {
311
- const validDayStarts = normalizedSessions
312
- .map((session) => toUtcDayStartMs(session.updatedAtMs))
313
- .filter((value) => Number.isFinite(value));
314
- const firstDayStart = validDayStarts.length ? Math.min(...validDayStarts) : toUtcDayStartMs(now);
315
- const lastDayStart = validDayStarts.length ? Math.max(...validDayStarts) : toUtcDayStartMs(now);
316
- for (let stamp = firstDayStart; stamp <= lastDayStart; stamp += dayMs) {
317
- const key = formatUtcDayKey(stamp);
318
- buckets.push({
319
- key,
320
- label: key.slice(5),
321
- codex: 0,
322
- claude: 0,
323
- totalMessages: 0,
324
- totalSessions: 0
325
- });
326
- }
327
- return { range, buckets };
328
- }
329
-
330
- const rangeDays = range === '30d' ? 30 : 7;
331
- for (let i = rangeDays - 1; i >= 0; i -= 1) {
332
- const stamp = new Date(now - (i * dayMs));
333
- const key = formatUtcDayKey(stamp);
334
- buckets.push({
335
- key,
336
- label: key.slice(5),
337
- codex: 0,
338
- claude: 0,
339
- totalMessages: 0,
340
- totalSessions: 0
341
- });
342
- }
343
- return { range, buckets };
344
- }
345
-
346
- export function buildUsageChartGroups(sessions = [], options = {}) {
347
- const list = Array.isArray(sessions) ? sessions : [];
348
- const normalizedSessions = [];
349
- for (const [sessionIndex, session] of list.entries()) {
350
- if (!session || typeof session !== 'object') continue;
351
- const source = normalizeSessionSource(session.source, '');
352
- if (source !== 'codex' && source !== 'claude') continue;
353
- const updatedAtMs = Date.parse(session.updatedAt || '');
354
- if (!Number.isFinite(updatedAtMs)) continue;
355
- const createdAtMs = Date.parse(session.createdAt || '');
356
- const sessionStartedAtMs = Number.isFinite(createdAtMs) ? createdAtMs : updatedAtMs;
357
- const sessionEndedAtMs = Math.max(updatedAtMs, sessionStartedAtMs);
358
- normalizedSessions.push({
359
- session,
360
- sessionIndex,
361
- source,
362
- updatedAtMs,
363
- createdAtMs,
364
- sessionStartedAtMs,
365
- sessionEndedAtMs,
366
- bucketKey: formatUtcDayKey(updatedAtMs)
367
- });
368
- }
369
- const { range, buckets } = buildUsageBuckets(normalizedSessions, options);
370
- const bucketMap = new Map(buckets.map((bucket) => [bucket.key, bucket]));
371
- let codexTotal = 0;
372
- let claudeTotal = 0;
373
- let messageTotal = 0;
374
- let totalTokens = 0;
375
- let totalContextWindow = 0;
376
- let activeDurationMs = 0;
377
- let earliestSessionMs = Number.POSITIVE_INFINITY;
378
- let latestSessionMs = 0;
379
- const pathMap = new Map();
380
- const modelMap = new Map();
381
- const missingModelProviderMap = new Map();
382
- const missingModelSessionMap = new Map();
383
- const sourceMessageTotals = { codex: 0, claude: 0 };
384
- const missingModelSourceTotals = { codex: 0, claude: 0 };
385
- let missingModelSessions = 0;
386
- let providerOnlySessions = 0;
387
- const hourCounts = Array.from({ length: 24 }, (_, hour) => ({
388
- key: String(hour).padStart(2, '0'),
389
- label: String(hour).padStart(2, '0'),
390
- count: 0
391
- }));
392
- const weekdayLabels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
393
- const weekdayCounts = Array.from({ length: 7 }, (_, index) => ({
394
- key: String(index),
395
- label: weekdayLabels[index],
396
- count: 0
397
- }));
398
- const recentSessions = [];
399
- const topSessionsByMessages = [];
400
- const filteredSessions = [];
401
-
402
- for (const normalized of normalizedSessions) {
403
- const { session, sessionIndex, source, updatedAtMs, sessionStartedAtMs, sessionEndedAtMs, bucketKey } = normalized;
404
- const stamp = new Date(updatedAtMs);
405
- const bucket = bucketMap.get(bucketKey);
406
- if (!bucket) continue;
407
- const sessionModels = collectSessionModelNames(session);
408
- if (sessionModels.length === 0) continue;
409
- filteredSessions.push(session);
410
- const messageCount = Number.isFinite(Number(session.messageCount))
411
- ? Math.max(0, Math.floor(Number(session.messageCount)))
412
- : 0;
413
- const sessionTotalTokens = readSessionTotalTokens(session);
414
- const sessionContextWindow = Number.isFinite(Number(session.contextWindow))
415
- ? Math.max(0, Math.floor(Number(session.contextWindow)))
416
- : 0;
417
- bucket.totalSessions += 1;
418
- bucket.totalMessages += messageCount;
419
- if (source === 'codex') {
420
- bucket.codex += 1;
421
- codexTotal += 1;
422
- } else {
423
- bucket.claude += 1;
424
- claudeTotal += 1;
425
- }
426
- messageTotal += messageCount;
427
- totalTokens += sessionTotalTokens;
428
- totalContextWindow += sessionContextWindow;
429
- sourceMessageTotals[source] += messageCount;
430
- activeDurationMs += Math.max(0, sessionEndedAtMs - sessionStartedAtMs);
431
- earliestSessionMs = Math.min(earliestSessionMs, sessionStartedAtMs);
432
- latestSessionMs = Math.max(latestSessionMs, sessionEndedAtMs);
433
-
434
- const utcHour = stamp.getUTCHours();
435
- if (hourCounts[utcHour]) {
436
- hourCounts[utcHour].count += 1;
437
- }
438
- const dayIndex = (stamp.getUTCDay() + 6) % 7;
439
- if (weekdayCounts[dayIndex]) {
440
- weekdayCounts[dayIndex].count += 1;
441
- }
442
-
443
- const cwd = normalizeSessionPathFilter(session.cwd);
444
- if (cwd) {
445
- const prev = pathMap.get(cwd) || { count: 0, messageTotal: 0, updatedAtMs: 0 };
446
- pathMap.set(cwd, {
447
- count: prev.count + 1,
448
- messageTotal: prev.messageTotal + messageCount,
449
- updatedAtMs: Math.max(prev.updatedAtMs, updatedAtMs)
450
- });
451
- }
452
-
453
- const sourceLabel = source === 'codex' ? 'Codex' : 'Claude Code';
454
- const normalizedTitle = typeof session.title === 'string' && session.title.trim()
455
- ? session.title.trim()
456
- : (typeof session.sessionId === 'string' && session.sessionId.trim() ? session.sessionId.trim() : '未命名会话');
457
- for (const modelId of sessionModels) {
458
- const prev = modelMap.get(modelId) || {
459
- count: 0,
460
- messageTotal: 0,
461
- tokenTotal: 0,
462
- sources: new Set()
463
- };
464
- prev.count += 1;
465
- prev.messageTotal += messageCount;
466
- prev.tokenTotal += sessionTotalTokens;
467
- prev.sources.add(source);
468
- modelMap.set(modelId, prev);
469
- }
470
-
471
- const sessionEntry = {
472
- key: [
473
- source,
474
- session.sessionId || '',
475
- session.filePath || normalizedTitle,
476
- String(updatedAtMs),
477
- String(messageCount),
478
- String(sessionIndex)
479
- ].join(':'),
480
- title: normalizedTitle,
481
- source,
482
- sourceLabel,
483
- cwd,
484
- messageCount,
485
- updatedAt: session.updatedAt || '',
486
- updatedAtMs,
487
- updatedAtLabel: formatSessionTimelineTimestamp(session.updatedAt || ''),
488
- hasExactMessageCount: session.__messageCountExact === true
489
- };
490
- recentSessions.push(sessionEntry);
491
- topSessionsByMessages.push({ ...sessionEntry });
492
- }
493
-
494
- const totalSessions = codexTotal + claudeTotal;
495
- const sourceShare = [
496
- { key: 'codex', label: 'Codex', value: codexTotal },
497
- { key: 'claude', label: 'Claude', value: claudeTotal }
498
- ].map((item) => ({
499
- ...item,
500
- percent: totalSessions > 0 ? Math.round((item.value / totalSessions) * 100) : 0,
501
- messageTotal: sourceMessageTotals[item.key] || 0,
502
- messagePercent: messageTotal > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / messageTotal) * 100) : 0,
503
- avgMessages: item.value > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / item.value) * 10) / 10 : 0
504
- }));
505
-
506
- const topPaths = [...pathMap.entries()]
507
- .sort((a, b) => b[1].count - a[1].count || b[1].messageTotal - a[1].messageTotal || a[0].localeCompare(b[0], 'zh-Hans-CN'))
508
- .slice(0, 5)
509
- .map(([pathValue, meta]) => ({
510
- path: pathValue,
511
- count: meta.count,
512
- messageTotal: meta.messageTotal,
513
- updatedAtLabel: meta.updatedAtMs ? formatSessionTimelineTimestamp(new Date(meta.updatedAtMs).toISOString()) : ''
514
- }));
515
-
516
- const usedModels = [...modelMap.entries()]
517
- .sort((a, b) => b[1].count - a[1].count)
518
- .map(([modelId, meta]) => {
519
- const sourceLabels = [...meta.sources]
520
- .sort((a, b) => a.localeCompare(b, 'en-US'))
521
- .map((source) => (source === 'codex' ? 'Codex' : 'Claude Code'));
522
- return {
523
- key: modelId,
524
- model: modelId,
525
- count: meta.count,
526
- messageTotal: meta.messageTotal,
527
- tokenTotal: meta.tokenTotal,
528
- sourceLabels
529
- };
530
- });
531
-
532
- const sortedRecentSessions = recentSessions
533
- .sort((a, b) => b.updatedAtMs - a.updatedAtMs || b.messageCount - a.messageCount || a.title.localeCompare(b.title, 'zh-Hans-CN'))
534
- .slice(0, 6);
535
-
536
- const missingModelProviders = [...missingModelProviderMap.values()]
537
- .sort((a, b) => b.count - a.count || a.label.localeCompare(b.label, 'zh-Hans-CN'));
538
- const missingModelSessionsPreview = [...missingModelSessionMap.values()]
539
- .sort((a, b) => b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
540
- .slice(0, 5);
541
-
542
- const modelCoverage = {
543
- totalSessions,
544
- modeledSessions: Math.max(0, totalSessions - missingModelSessions),
545
- missingModelSessions,
546
- providerOnlySessions,
547
- missingModelSourceTotals,
548
- missingModelProviders,
549
- missingModelSessionsPreview,
550
- coveragePercent: totalSessions > 0 ? Math.round(((totalSessions - missingModelSessions) / totalSessions) * 100) : 0
551
- };
552
-
553
- const sortedTopSessionsByMessages = topSessionsByMessages
554
- .sort((a, b) => b.messageCount - a.messageCount || b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
555
- .slice(0, 6);
556
-
557
- const maxSessionBucket = buckets.reduce((max, item) => Math.max(max, item.totalSessions), 0);
558
- const maxMessageBucket = buckets.reduce((max, item) => Math.max(max, item.totalMessages), 0);
559
- const maxHourCount = hourCounts.reduce((max, item) => Math.max(max, item.count), 0);
560
- const maxWeekdayCount = weekdayCounts.reduce((max, item) => Math.max(max, item.count), 0);
561
- const busiestDay = [...buckets]
562
- .sort((a, b) => b.totalSessions - a.totalSessions || b.totalMessages - a.totalMessages || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
563
- const busiestHour = [...hourCounts]
564
- .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
565
- const activeDays = buckets.filter((item) => item.totalSessions > 0).length;
566
- const avgMessagesPerSession = totalSessions > 0 ? Math.round((messageTotal / totalSessions) * 10) / 10 : 0;
567
- const avgSessionsPerActiveDay = activeDays > 0 ? Math.round((totalSessions / activeDays) * 10) / 10 : 0;
568
- const totalDurationMs = Number.isFinite(earliestSessionMs) && latestSessionMs > 0
569
- ? Math.max(0, latestSessionMs - earliestSessionMs)
570
- : 0;
571
-
572
- return {
573
- range,
574
- buckets,
575
- filteredSessions,
576
- summary: {
577
- totalSessions,
578
- totalMessages: messageTotal,
579
- totalTokens,
580
- totalContextWindow,
581
- activeDurationMs,
582
- totalDurationMs,
583
- codexTotal,
584
- claudeTotal,
585
- activeDays,
586
- avgMessagesPerSession,
587
- avgSessionsPerActiveDay,
588
- busiestDay: busiestDay
589
- ? {
590
- key: busiestDay.key,
591
- label: busiestDay.label,
592
- totalSessions: busiestDay.totalSessions,
593
- totalMessages: busiestDay.totalMessages
594
- }
595
- : null,
596
- busiestHour: busiestHour
597
- ? {
598
- key: busiestHour.key,
599
- label: `${busiestHour.label}:00`,
600
- count: busiestHour.count
601
- }
602
- : null
603
- },
604
- sourceShare,
605
- usedModels,
606
- modelCoverage,
607
- topPaths,
608
- recentSessions: sortedRecentSessions,
609
- topSessionsByMessages: sortedTopSessionsByMessages,
610
- hourActivity: hourCounts.map((item) => ({
611
- ...item,
612
- percent: maxHourCount > 0 ? Math.round((item.count / maxHourCount) * 100) : 0
613
- })),
614
- weekdayActivity: weekdayCounts.map((item) => ({
615
- ...item,
616
- percent: maxWeekdayCount > 0 ? Math.round((item.count / maxWeekdayCount) * 100) : 0
617
- })),
618
- maxSessionBucket,
619
- maxMessageBucket,
620
- maxHourCount,
621
- maxWeekdayCount
622
- };
623
- }
624
-
625
- export function buildSessionTimelineNodes(messages = [], options = {}) {
626
- const list = Array.isArray(messages) ? messages : [];
627
- const getKey = typeof options.getKey === 'function'
628
- ? options.getKey
629
- : ((_message, index) => `msg-${index}`);
630
- const total = list.length;
631
- const rawMaxMarkers = Number(options.maxMarkers);
632
- const maxMarkers = Number.isFinite(rawMaxMarkers)
633
- ? Math.max(1, Math.min(80, Math.floor(rawMaxMarkers)))
634
- : 30;
635
-
636
- const buildSingleNode = (message, index) => {
637
- const role = normalizeSessionMessageRole(message && (message.normalizedRole || message.role));
638
- const roleMeta = toRoleMeta(role);
639
- const key = String(getKey(message, index) || `msg-${index}`);
640
- const displayTime = formatSessionTimelineTimestamp(message && message.timestamp ? message.timestamp : '');
641
- const title = displayTime
642
- ? `#${index + 1} · ${roleMeta.roleLabel} · ${displayTime}`
643
- : `#${index + 1} · ${roleMeta.roleLabel}`;
644
- const percent = total <= 1 ? 0 : (index / (total - 1)) * 100;
645
- return {
646
- key,
647
- role: roleMeta.role,
648
- roleLabel: roleMeta.roleLabel,
649
- roleShort: roleMeta.roleShort,
650
- displayTime,
651
- title,
652
- percent,
653
- safePercent: clampTimelinePercent(percent)
654
- };
655
- };
656
-
657
- if (total <= maxMarkers) {
658
- return list.map((message, index) => buildSingleNode(message, index));
659
- }
660
-
661
- const nodes = [];
662
- const bucketWidth = total / maxMarkers;
663
- for (let bucket = 0; bucket < maxMarkers; bucket += 1) {
664
- let start = Math.floor(bucket * bucketWidth);
665
- if (nodes.length && start <= nodes[nodes.length - 1].endIndex) {
666
- start = nodes[nodes.length - 1].endIndex + 1;
667
- }
668
- if (start >= total) {
669
- break;
670
- }
671
- let end = Math.floor((bucket + 1) * bucketWidth) - 1;
672
- end = Math.max(start, Math.min(total - 1, end));
673
- const targetIndex = Math.min(total - 1, start + Math.floor((end - start) / 2));
674
- const targetMessage = list[targetIndex] || null;
675
- const key = String(getKey(targetMessage, targetIndex) || `msg-${targetIndex}`);
676
- const percent = total <= 1 ? 0 : (targetIndex / (total - 1)) * 100;
677
- const messagesInGroup = end - start + 1;
678
- const roleSet = new Set();
679
- for (let i = start; i <= end; i += 1) {
680
- roleSet.add(normalizeSessionMessageRole(list[i] && (list[i].normalizedRole || list[i].role)));
681
- }
682
- const roleValue = roleSet.size === 1 ? Array.from(roleSet)[0] : 'mixed';
683
- const roleMeta = toRoleMeta(roleValue);
684
- const firstTime = formatSessionTimelineTimestamp(list[start] && list[start].timestamp ? list[start].timestamp : '');
685
- const lastTime = formatSessionTimelineTimestamp(list[end] && list[end].timestamp ? list[end].timestamp : '');
686
- let displayTime = '';
687
- if (firstTime && lastTime) {
688
- displayTime = firstTime === lastTime ? firstTime : `${firstTime} ~ ${lastTime}`;
689
- } else {
690
- displayTime = firstTime || lastTime;
691
- }
692
- const titleBase = `#${start + 1}-${end + 1} · ${messagesInGroup} msgs · ${roleMeta.roleLabel}`;
693
- const title = displayTime ? `${titleBase} · ${displayTime}` : titleBase;
694
- nodes.push({
695
- key,
696
- role: roleMeta.role,
697
- roleLabel: roleMeta.roleLabel,
698
- roleShort: roleMeta.roleShort,
699
- displayTime,
700
- title,
701
- percent,
702
- safePercent: clampTimelinePercent(percent),
703
- startIndex: start,
704
- endIndex: end,
705
- messageCount: messagesInGroup
706
- });
707
- }
708
- return nodes;
709
- }
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 === 'gemini' || normalized === 'codebuddy' || 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 === 'gemini' || normalized === 'codebuddy' || 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
+ export function buildUsageHeatmap(sessions = [], options = {}) {
210
+ const list = Array.isArray(sessions) ? sessions : [];
211
+ const normalized = [];
212
+ for (const session of list) {
213
+ if (!session || typeof session !== 'object') continue;
214
+ const source = normalizeSessionSource(session.source, '');
215
+ if (source !== 'codex' && source !== 'claude') continue;
216
+ const updatedAtMs = Date.parse(session.updatedAt || '');
217
+ if (!Number.isFinite(updatedAtMs)) continue;
218
+ normalized.push({
219
+ updatedAtMs,
220
+ messageCount: Number.isFinite(Number(session.messageCount))
221
+ ? Math.max(0, Math.floor(Number(session.messageCount)))
222
+ : 0,
223
+ tokenTotal: readSessionTotalTokens(session)
224
+ });
225
+ }
226
+
227
+ const range = normalizeUsageRange(options.range);
228
+ const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
229
+ const dayMs = 24 * 60 * 60 * 1000;
230
+ const todayStart = toUtcDayStartMs(now);
231
+ let startDay = todayStart;
232
+ let endDay = todayStart;
233
+ if (range === 'all') {
234
+ const dayStarts = normalized.map((item) => toUtcDayStartMs(item.updatedAtMs)).filter((value) => Number.isFinite(value));
235
+ if (dayStarts.length) {
236
+ startDay = Math.min(...dayStarts);
237
+ endDay = Math.max(...dayStarts);
238
+ }
239
+ } else {
240
+ const rangeDays = range === '30d' ? 30 : 7;
241
+ endDay = todayStart;
242
+ startDay = todayStart - ((rangeDays - 1) * dayMs);
243
+ }
244
+
245
+ const startDow = new Date(startDay).getUTCDay();
246
+ const startShift = (startDow + 6) % 7;
247
+ const alignedStart = startDay - (startShift * dayMs);
248
+ const endDow = new Date(endDay).getUTCDay();
249
+ const endShift = (6 - ((endDow + 6) % 7));
250
+ const alignedEnd = endDay + (endShift * dayMs);
251
+ const totalDays = Math.floor((alignedEnd - alignedStart) / dayMs) + 1;
252
+ const weekCount = Math.max(1, Math.ceil(totalDays / 7));
253
+
254
+ const byDay = new Map();
255
+ for (const item of normalized) {
256
+ const dayKey = formatUtcDayKey(item.updatedAtMs);
257
+ const existing = byDay.get(dayKey) || { sessionCount: 0, messageCount: 0, tokenTotal: 0 };
258
+ existing.sessionCount += 1;
259
+ existing.messageCount += item.messageCount;
260
+ existing.tokenTotal += item.tokenTotal;
261
+ byDay.set(dayKey, existing);
262
+ }
263
+
264
+ const weeks = Array.from({ length: weekCount }, (_, idx) => ({
265
+ key: `w-${idx}`,
266
+ weekIndex: idx,
267
+ days: Array.from({ length: 7 }, () => null)
268
+ }));
269
+
270
+ let maxSessionCount = 0;
271
+ for (let dayIndex = 0; dayIndex < totalDays; dayIndex += 1) {
272
+ const dateMs = alignedStart + (dayIndex * dayMs);
273
+ const dateKey = formatUtcDayKey(dateMs);
274
+ const isInRange = dateMs >= startDay && dateMs <= endDay;
275
+ const weekIndex = Math.floor(dayIndex / 7);
276
+ const dow = new Date(dateMs).getUTCDay();
277
+ const rowIndex = (dow + 6) % 7;
278
+ const totals = isInRange ? (byDay.get(dateKey) || { sessionCount: 0, messageCount: 0, tokenTotal: 0 }) : null;
279
+ const sessionCount = totals ? totals.sessionCount : 0;
280
+ if (isInRange) {
281
+ maxSessionCount = Math.max(maxSessionCount, sessionCount);
282
+ }
283
+ weeks[weekIndex].days[rowIndex] = {
284
+ dateKey,
285
+ dateMs,
286
+ isInRange,
287
+ sessionCount,
288
+ messageCount: totals ? totals.messageCount : 0,
289
+ tokenTotal: totals ? totals.tokenTotal : 0
290
+ };
291
+ }
292
+
293
+ return {
294
+ range,
295
+ startDay,
296
+ endDay,
297
+ alignedStart,
298
+ alignedEnd,
299
+ maxSessionCount,
300
+ weeks
301
+ };
302
+ }
303
+
304
+ export function buildUsageHourlyHeatmap(sessions = [], options = {}) {
305
+ const list = Array.isArray(sessions) ? sessions : [];
306
+ const range = normalizeUsageRange(options.range);
307
+ const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
308
+ const dayMs = 24 * 60 * 60 * 1000;
309
+ const todayStart = toUtcDayStartMs(now);
310
+
311
+ const normalized = [];
312
+ for (const session of list) {
313
+ if (!session || typeof session !== 'object') continue;
314
+ const source = normalizeSessionSource(session.source, '');
315
+ if (source !== 'codex' && source !== 'claude') continue;
316
+ const updatedAtMs = Date.parse(session.updatedAt || '');
317
+ if (!Number.isFinite(updatedAtMs)) continue;
318
+ const dayStart = toUtcDayStartMs(updatedAtMs);
319
+ if (range !== 'all') {
320
+ const rangeDays = range === '30d' ? 30 : 7;
321
+ const rangeStart = todayStart - ((rangeDays - 1) * dayMs);
322
+ if (dayStart < rangeStart || dayStart > todayStart) continue;
323
+ }
324
+ const stamp = new Date(updatedAtMs);
325
+ const weekday = (stamp.getUTCDay() + 6) % 7;
326
+ const hour = stamp.getUTCHours();
327
+ const messageCount = Number.isFinite(Number(session.messageCount))
328
+ ? Math.max(0, Math.floor(Number(session.messageCount)))
329
+ : 0;
330
+ const tokenTotal = readSessionTotalTokens(session);
331
+ normalized.push({ weekday, hour, messageCount, tokenTotal });
332
+ }
333
+
334
+ const grid = Array.from({ length: 7 }, () =>
335
+ Array.from({ length: 24 }, () => ({ sessionCount: 0, messageCount: 0, tokenTotal: 0 }))
336
+ );
337
+ for (const item of normalized) {
338
+ const cell = grid[item.weekday][item.hour];
339
+ cell.sessionCount += 1;
340
+ cell.messageCount += item.messageCount;
341
+ cell.tokenTotal += item.tokenTotal;
342
+ }
343
+
344
+ let maxSessionCount = 0;
345
+ for (let day = 0; day < 7; day += 1) {
346
+ for (let hour = 0; hour < 24; hour += 1) {
347
+ maxSessionCount = Math.max(maxSessionCount, grid[day][hour].sessionCount);
348
+ }
349
+ }
350
+
351
+ return {
352
+ range,
353
+ grid,
354
+ maxSessionCount: Math.max(1, maxSessionCount),
355
+ weekdayKeys: [0, 1, 2, 3, 4, 5, 6],
356
+ hourLabels: Array.from({ length: 24 }, (_, index) => String(index).padStart(2, '0'))
357
+ };
358
+ }
359
+
360
+ function buildUsageBuckets(normalizedSessions, options = {}) {
361
+ const range = normalizeUsageRange(options.range);
362
+ const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
363
+ const dayMs = 24 * 60 * 60 * 1000;
364
+ const buckets = [];
365
+
366
+ if (range === 'all') {
367
+ const validDayStarts = normalizedSessions
368
+ .map((session) => toUtcDayStartMs(session.updatedAtMs))
369
+ .filter((value) => Number.isFinite(value));
370
+ const firstDayStart = validDayStarts.length ? Math.min(...validDayStarts) : toUtcDayStartMs(now);
371
+ const lastDayStart = validDayStarts.length ? Math.max(...validDayStarts) : toUtcDayStartMs(now);
372
+ for (let stamp = firstDayStart; stamp <= lastDayStart; stamp += dayMs) {
373
+ const key = formatUtcDayKey(stamp);
374
+ buckets.push({
375
+ key,
376
+ label: key.slice(5),
377
+ codex: 0,
378
+ claude: 0,
379
+ totalMessages: 0,
380
+ totalSessions: 0
381
+ });
382
+ }
383
+ return { range, buckets };
384
+ }
385
+
386
+ const rangeDays = range === '30d' ? 30 : 7;
387
+ for (let i = rangeDays - 1; i >= 0; i -= 1) {
388
+ const stamp = new Date(now - (i * dayMs));
389
+ const key = formatUtcDayKey(stamp);
390
+ buckets.push({
391
+ key,
392
+ label: key.slice(5),
393
+ codex: 0,
394
+ claude: 0,
395
+ totalMessages: 0,
396
+ totalSessions: 0
397
+ });
398
+ }
399
+ return { range, buckets };
400
+ }
401
+
402
+ export function buildUsageChartGroups(sessions = [], options = {}) {
403
+ const list = Array.isArray(sessions) ? sessions : [];
404
+ const normalizedSessions = [];
405
+ for (const [sessionIndex, session] of list.entries()) {
406
+ if (!session || typeof session !== 'object') continue;
407
+ const source = normalizeSessionSource(session.source, '');
408
+ if (source !== 'codex' && source !== 'claude') continue;
409
+ const updatedAtMs = Date.parse(session.updatedAt || '');
410
+ if (!Number.isFinite(updatedAtMs)) continue;
411
+ const createdAtMs = Date.parse(session.createdAt || '');
412
+ const sessionStartedAtMs = Number.isFinite(createdAtMs) ? createdAtMs : updatedAtMs;
413
+ const sessionEndedAtMs = Math.max(updatedAtMs, sessionStartedAtMs);
414
+ normalizedSessions.push({
415
+ session,
416
+ sessionIndex,
417
+ source,
418
+ updatedAtMs,
419
+ createdAtMs,
420
+ sessionStartedAtMs,
421
+ sessionEndedAtMs,
422
+ bucketKey: formatUtcDayKey(updatedAtMs)
423
+ });
424
+ }
425
+ const { range, buckets } = buildUsageBuckets(normalizedSessions, options);
426
+ const bucketMap = new Map(buckets.map((bucket) => [bucket.key, bucket]));
427
+ let codexTotal = 0;
428
+ let claudeTotal = 0;
429
+ let messageTotal = 0;
430
+ let totalTokens = 0;
431
+ let totalContextWindow = 0;
432
+ let activeDurationMs = 0;
433
+ let earliestSessionMs = Number.POSITIVE_INFINITY;
434
+ let latestSessionMs = 0;
435
+ const pathMap = new Map();
436
+ const modelMap = new Map();
437
+ const missingModelProviderMap = new Map();
438
+ const missingModelSessionMap = new Map();
439
+ const sourceMessageTotals = { codex: 0, claude: 0 };
440
+ const missingModelSourceTotals = { codex: 0, claude: 0 };
441
+ let missingModelSessions = 0;
442
+ let providerOnlySessions = 0;
443
+ const hourCounts = Array.from({ length: 24 }, (_, hour) => ({
444
+ key: String(hour).padStart(2, '0'),
445
+ label: String(hour).padStart(2, '0'),
446
+ count: 0
447
+ }));
448
+ const weekdayLabels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
449
+ const weekdayCounts = Array.from({ length: 7 }, (_, index) => ({
450
+ key: String(index),
451
+ label: weekdayLabels[index],
452
+ count: 0
453
+ }));
454
+ const recentSessions = [];
455
+ const topSessionsByMessages = [];
456
+ const filteredSessions = [];
457
+
458
+ for (const normalized of normalizedSessions) {
459
+ const { session, sessionIndex, source, updatedAtMs, sessionStartedAtMs, sessionEndedAtMs, bucketKey } = normalized;
460
+ const stamp = new Date(updatedAtMs);
461
+ const bucket = bucketMap.get(bucketKey);
462
+ if (!bucket) continue;
463
+ const sessionModels = collectSessionModelNames(session);
464
+ if (sessionModels.length === 0) continue;
465
+ filteredSessions.push(session);
466
+ const messageCount = Number.isFinite(Number(session.messageCount))
467
+ ? Math.max(0, Math.floor(Number(session.messageCount)))
468
+ : 0;
469
+ const sessionTotalTokens = readSessionTotalTokens(session);
470
+ const sessionContextWindow = Number.isFinite(Number(session.contextWindow))
471
+ ? Math.max(0, Math.floor(Number(session.contextWindow)))
472
+ : 0;
473
+ bucket.totalSessions += 1;
474
+ bucket.totalMessages += messageCount;
475
+ if (source === 'codex') {
476
+ bucket.codex += 1;
477
+ codexTotal += 1;
478
+ } else {
479
+ bucket.claude += 1;
480
+ claudeTotal += 1;
481
+ }
482
+ messageTotal += messageCount;
483
+ totalTokens += sessionTotalTokens;
484
+ totalContextWindow += sessionContextWindow;
485
+ sourceMessageTotals[source] += messageCount;
486
+ activeDurationMs += Math.max(0, sessionEndedAtMs - sessionStartedAtMs);
487
+ earliestSessionMs = Math.min(earliestSessionMs, sessionStartedAtMs);
488
+ latestSessionMs = Math.max(latestSessionMs, sessionEndedAtMs);
489
+
490
+ const utcHour = stamp.getUTCHours();
491
+ if (hourCounts[utcHour]) {
492
+ hourCounts[utcHour].count += 1;
493
+ }
494
+ const dayIndex = (stamp.getUTCDay() + 6) % 7;
495
+ if (weekdayCounts[dayIndex]) {
496
+ weekdayCounts[dayIndex].count += 1;
497
+ }
498
+
499
+ const cwd = normalizeSessionPathFilter(session.cwd);
500
+ if (cwd) {
501
+ const prev = pathMap.get(cwd) || { count: 0, messageTotal: 0, updatedAtMs: 0 };
502
+ pathMap.set(cwd, {
503
+ count: prev.count + 1,
504
+ messageTotal: prev.messageTotal + messageCount,
505
+ updatedAtMs: Math.max(prev.updatedAtMs, updatedAtMs)
506
+ });
507
+ }
508
+
509
+ const sourceLabel = source === 'codex' ? 'Codex' : 'Claude Code';
510
+ const normalizedTitle = typeof session.title === 'string' && session.title.trim()
511
+ ? session.title.trim()
512
+ : (typeof session.sessionId === 'string' && session.sessionId.trim() ? session.sessionId.trim() : '未命名会话');
513
+ for (const modelId of sessionModels) {
514
+ const prev = modelMap.get(modelId) || {
515
+ count: 0,
516
+ messageTotal: 0,
517
+ tokenTotal: 0,
518
+ sources: new Set()
519
+ };
520
+ prev.count += 1;
521
+ prev.messageTotal += messageCount;
522
+ prev.tokenTotal += sessionTotalTokens;
523
+ prev.sources.add(source);
524
+ modelMap.set(modelId, prev);
525
+ }
526
+
527
+ const sessionEntry = {
528
+ key: [
529
+ source,
530
+ session.sessionId || '',
531
+ session.filePath || normalizedTitle,
532
+ String(updatedAtMs),
533
+ String(messageCount),
534
+ String(sessionIndex)
535
+ ].join(':'),
536
+ title: normalizedTitle,
537
+ source,
538
+ sourceLabel,
539
+ cwd,
540
+ messageCount,
541
+ updatedAt: session.updatedAt || '',
542
+ updatedAtMs,
543
+ updatedAtLabel: formatSessionTimelineTimestamp(session.updatedAt || ''),
544
+ hasExactMessageCount: session.__messageCountExact === true
545
+ };
546
+ recentSessions.push(sessionEntry);
547
+ topSessionsByMessages.push({ ...sessionEntry });
548
+ }
549
+
550
+ const totalSessions = codexTotal + claudeTotal;
551
+ const sourceShare = [
552
+ { key: 'codex', label: 'Codex', value: codexTotal },
553
+ { key: 'claude', label: 'Claude', value: claudeTotal }
554
+ ].map((item) => ({
555
+ ...item,
556
+ percent: totalSessions > 0 ? Math.round((item.value / totalSessions) * 100) : 0,
557
+ messageTotal: sourceMessageTotals[item.key] || 0,
558
+ messagePercent: messageTotal > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / messageTotal) * 100) : 0,
559
+ avgMessages: item.value > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / item.value) * 10) / 10 : 0
560
+ }));
561
+
562
+ const topPaths = [...pathMap.entries()]
563
+ .sort((a, b) => b[1].count - a[1].count || b[1].messageTotal - a[1].messageTotal || a[0].localeCompare(b[0], 'zh-Hans-CN'))
564
+ .slice(0, 5)
565
+ .map(([pathValue, meta]) => ({
566
+ path: pathValue,
567
+ count: meta.count,
568
+ messageTotal: meta.messageTotal,
569
+ updatedAtLabel: meta.updatedAtMs ? formatSessionTimelineTimestamp(new Date(meta.updatedAtMs).toISOString()) : ''
570
+ }));
571
+
572
+ const usedModels = [...modelMap.entries()]
573
+ .sort((a, b) => b[1].count - a[1].count)
574
+ .map(([modelId, meta]) => {
575
+ const sourceLabels = [...meta.sources]
576
+ .sort((a, b) => a.localeCompare(b, 'en-US'))
577
+ .map((source) => (source === 'codex' ? 'Codex' : 'Claude Code'));
578
+ return {
579
+ key: modelId,
580
+ model: modelId,
581
+ count: meta.count,
582
+ messageTotal: meta.messageTotal,
583
+ tokenTotal: meta.tokenTotal,
584
+ sourceLabels
585
+ };
586
+ });
587
+
588
+ const sortedRecentSessions = recentSessions
589
+ .sort((a, b) => b.updatedAtMs - a.updatedAtMs || b.messageCount - a.messageCount || a.title.localeCompare(b.title, 'zh-Hans-CN'))
590
+ .slice(0, 6);
591
+
592
+ const missingModelProviders = [...missingModelProviderMap.values()]
593
+ .sort((a, b) => b.count - a.count || a.label.localeCompare(b.label, 'zh-Hans-CN'));
594
+ const missingModelSessionsPreview = [...missingModelSessionMap.values()]
595
+ .sort((a, b) => b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
596
+ .slice(0, 5);
597
+
598
+ const modelCoverage = {
599
+ totalSessions,
600
+ modeledSessions: Math.max(0, totalSessions - missingModelSessions),
601
+ missingModelSessions,
602
+ providerOnlySessions,
603
+ missingModelSourceTotals,
604
+ missingModelProviders,
605
+ missingModelSessionsPreview,
606
+ coveragePercent: totalSessions > 0 ? Math.round(((totalSessions - missingModelSessions) / totalSessions) * 100) : 0
607
+ };
608
+
609
+ const sortedTopSessionsByMessages = topSessionsByMessages
610
+ .sort((a, b) => b.messageCount - a.messageCount || b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
611
+ .slice(0, 6);
612
+
613
+ const maxSessionBucket = buckets.reduce((max, item) => Math.max(max, item.totalSessions), 0);
614
+ const maxMessageBucket = buckets.reduce((max, item) => Math.max(max, item.totalMessages), 0);
615
+ const maxHourCount = hourCounts.reduce((max, item) => Math.max(max, item.count), 0);
616
+ const maxWeekdayCount = weekdayCounts.reduce((max, item) => Math.max(max, item.count), 0);
617
+ const busiestDay = [...buckets]
618
+ .sort((a, b) => b.totalSessions - a.totalSessions || b.totalMessages - a.totalMessages || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
619
+ const busiestHour = [...hourCounts]
620
+ .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
621
+ const activeDays = buckets.filter((item) => item.totalSessions > 0).length;
622
+ const avgMessagesPerSession = totalSessions > 0 ? Math.round((messageTotal / totalSessions) * 10) / 10 : 0;
623
+ const avgSessionsPerActiveDay = activeDays > 0 ? Math.round((totalSessions / activeDays) * 10) / 10 : 0;
624
+ const totalDurationMs = Number.isFinite(earliestSessionMs) && latestSessionMs > 0
625
+ ? Math.max(0, latestSessionMs - earliestSessionMs)
626
+ : 0;
627
+
628
+ return {
629
+ range,
630
+ buckets,
631
+ filteredSessions,
632
+ summary: {
633
+ totalSessions,
634
+ totalMessages: messageTotal,
635
+ totalTokens,
636
+ totalContextWindow,
637
+ activeDurationMs,
638
+ totalDurationMs,
639
+ codexTotal,
640
+ claudeTotal,
641
+ activeDays,
642
+ avgMessagesPerSession,
643
+ avgSessionsPerActiveDay,
644
+ busiestDay: busiestDay
645
+ ? {
646
+ key: busiestDay.key,
647
+ label: busiestDay.label,
648
+ totalSessions: busiestDay.totalSessions,
649
+ totalMessages: busiestDay.totalMessages
650
+ }
651
+ : null,
652
+ busiestHour: busiestHour
653
+ ? {
654
+ key: busiestHour.key,
655
+ label: `${busiestHour.label}:00`,
656
+ count: busiestHour.count
657
+ }
658
+ : null
659
+ },
660
+ sourceShare,
661
+ usedModels,
662
+ modelCoverage,
663
+ topPaths,
664
+ recentSessions: sortedRecentSessions,
665
+ topSessionsByMessages: sortedTopSessionsByMessages,
666
+ hourActivity: hourCounts.map((item) => ({
667
+ ...item,
668
+ percent: maxHourCount > 0 ? Math.round((item.count / maxHourCount) * 100) : 0
669
+ })),
670
+ weekdayActivity: weekdayCounts.map((item) => ({
671
+ ...item,
672
+ percent: maxWeekdayCount > 0 ? Math.round((item.count / maxWeekdayCount) * 100) : 0
673
+ })),
674
+ maxSessionBucket,
675
+ maxMessageBucket,
676
+ maxHourCount,
677
+ maxWeekdayCount
678
+ };
679
+ }
680
+
681
+ export function buildSessionTimelineNodes(messages = [], options = {}) {
682
+ const list = Array.isArray(messages) ? messages : [];
683
+ const getKey = typeof options.getKey === 'function'
684
+ ? options.getKey
685
+ : ((_message, index) => `msg-${index}`);
686
+ const total = list.length;
687
+ const rawMaxMarkers = Number(options.maxMarkers);
688
+ const maxMarkers = Number.isFinite(rawMaxMarkers)
689
+ ? Math.max(1, Math.min(80, Math.floor(rawMaxMarkers)))
690
+ : 30;
691
+
692
+ const buildSingleNode = (message, index) => {
693
+ const role = normalizeSessionMessageRole(message && (message.normalizedRole || message.role));
694
+ const roleMeta = toRoleMeta(role);
695
+ const key = String(getKey(message, index) || `msg-${index}`);
696
+ const displayTime = formatSessionTimelineTimestamp(message && message.timestamp ? message.timestamp : '');
697
+ const title = displayTime
698
+ ? `#${index + 1} · ${roleMeta.roleLabel} · ${displayTime}`
699
+ : `#${index + 1} · ${roleMeta.roleLabel}`;
700
+ const percent = total <= 1 ? 0 : (index / (total - 1)) * 100;
701
+ return {
702
+ key,
703
+ role: roleMeta.role,
704
+ roleLabel: roleMeta.roleLabel,
705
+ roleShort: roleMeta.roleShort,
706
+ displayTime,
707
+ title,
708
+ percent,
709
+ safePercent: clampTimelinePercent(percent)
710
+ };
711
+ };
712
+
713
+ if (total <= maxMarkers) {
714
+ return list.map((message, index) => buildSingleNode(message, index));
715
+ }
716
+
717
+ const nodes = [];
718
+ const bucketWidth = total / maxMarkers;
719
+ for (let bucket = 0; bucket < maxMarkers; bucket += 1) {
720
+ let start = Math.floor(bucket * bucketWidth);
721
+ if (nodes.length && start <= nodes[nodes.length - 1].endIndex) {
722
+ start = nodes[nodes.length - 1].endIndex + 1;
723
+ }
724
+ if (start >= total) {
725
+ break;
726
+ }
727
+ let end = Math.floor((bucket + 1) * bucketWidth) - 1;
728
+ end = Math.max(start, Math.min(total - 1, end));
729
+ const targetIndex = Math.min(total - 1, start + Math.floor((end - start) / 2));
730
+ const targetMessage = list[targetIndex] || null;
731
+ const key = String(getKey(targetMessage, targetIndex) || `msg-${targetIndex}`);
732
+ const percent = total <= 1 ? 0 : (targetIndex / (total - 1)) * 100;
733
+ const messagesInGroup = end - start + 1;
734
+ const roleSet = new Set();
735
+ for (let i = start; i <= end; i += 1) {
736
+ roleSet.add(normalizeSessionMessageRole(list[i] && (list[i].normalizedRole || list[i].role)));
737
+ }
738
+ const roleValue = roleSet.size === 1 ? Array.from(roleSet)[0] : 'mixed';
739
+ const roleMeta = toRoleMeta(roleValue);
740
+ const firstTime = formatSessionTimelineTimestamp(list[start] && list[start].timestamp ? list[start].timestamp : '');
741
+ const lastTime = formatSessionTimelineTimestamp(list[end] && list[end].timestamp ? list[end].timestamp : '');
742
+ let displayTime = '';
743
+ if (firstTime && lastTime) {
744
+ displayTime = firstTime === lastTime ? firstTime : `${firstTime} ~ ${lastTime}`;
745
+ } else {
746
+ displayTime = firstTime || lastTime;
747
+ }
748
+ const titleBase = `#${start + 1}-${end + 1} · ${messagesInGroup} msgs · ${roleMeta.roleLabel}`;
749
+ const title = displayTime ? `${titleBase} · ${displayTime}` : titleBase;
750
+ nodes.push({
751
+ key,
752
+ role: roleMeta.role,
753
+ roleLabel: roleMeta.roleLabel,
754
+ roleShort: roleMeta.roleShort,
755
+ displayTime,
756
+ title,
757
+ percent,
758
+ safePercent: clampTimelinePercent(percent),
759
+ startIndex: start,
760
+ endIndex: end,
761
+ messageCount: messagesInGroup
762
+ });
763
+ }
764
+ return nodes;
765
+ }