codexmate 0.0.27 → 0.0.28

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 (137) hide show
  1. package/README.md +421 -421
  2. package/README.zh.md +354 -354
  3. package/cli/agents-files.js +224 -224
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +375 -375
  6. package/cli/builtin-proxy.js +1620 -1299
  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 +1489 -1091
  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 +15264 -15251
  23. package/lib/automation.js +404 -404
  24. package/lib/cli-file-utils.js +151 -151
  25. package/lib/cli-models-utils.js +440 -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 +3 -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 +553 -619
  44. package/plugins/prompt-templates/overview.mjs +91 -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 +625 -634
  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.codex.mjs +56 -0
  54. package/web-ui/logic.mjs +5 -5
  55. package/web-ui/logic.runtime.mjs +128 -128
  56. package/web-ui/logic.session-convert.mjs +70 -70
  57. package/web-ui/logic.sessions.mjs +765 -765
  58. package/web-ui/modules/api.mjs +90 -90
  59. package/web-ui/modules/app.computed.dashboard.mjs +225 -171
  60. package/web-ui/modules/app.computed.index.mjs +17 -17
  61. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  62. package/web-ui/modules/app.computed.session.mjs +994 -994
  63. package/web-ui/modules/app.constants.mjs +15 -15
  64. package/web-ui/modules/app.methods.agents.mjs +632 -632
  65. package/web-ui/modules/app.methods.claude-config.mjs +190 -184
  66. package/web-ui/modules/app.methods.codex-config.mjs +892 -860
  67. package/web-ui/modules/app.methods.index.mjs +92 -92
  68. package/web-ui/modules/app.methods.install.mjs +205 -205
  69. package/web-ui/modules/app.methods.navigation.mjs +743 -743
  70. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  71. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  72. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  73. package/web-ui/modules/app.methods.providers.mjs +412 -404
  74. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  75. package/web-ui/modules/app.methods.session-actions.mjs +593 -596
  76. package/web-ui/modules/app.methods.session-browser.mjs +984 -989
  77. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  78. package/web-ui/modules/app.methods.session-trash.mjs +439 -439
  79. package/web-ui/modules/app.methods.startup-claude.mjs +533 -526
  80. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  81. package/web-ui/modules/config-mode.computed.mjs +124 -124
  82. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  83. package/web-ui/modules/i18n.dict.mjs +2109 -2131
  84. package/web-ui/modules/i18n.mjs +56 -56
  85. package/web-ui/modules/plugins.computed.mjs +3 -3
  86. package/web-ui/modules/plugins.methods.mjs +3 -3
  87. package/web-ui/modules/plugins.storage.mjs +11 -11
  88. package/web-ui/modules/provider-url-display.mjs +17 -0
  89. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  90. package/web-ui/modules/skills.computed.mjs +107 -107
  91. package/web-ui/modules/skills.methods.mjs +481 -481
  92. package/web-ui/partials/index/layout-footer.html +13 -13
  93. package/web-ui/partials/index/layout-header.html +475 -475
  94. package/web-ui/partials/index/modal-config-template-agents.html +174 -174
  95. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  96. package/web-ui/partials/index/modal-health-check.html +45 -45
  97. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  98. package/web-ui/partials/index/modal-skills.html +200 -200
  99. package/web-ui/partials/index/modals-basic.html +165 -165
  100. package/web-ui/partials/index/panel-config-claude.html +188 -187
  101. package/web-ui/partials/index/panel-config-codex.html +312 -283
  102. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  103. package/web-ui/partials/index/panel-dashboard.html +186 -186
  104. package/web-ui/partials/index/panel-docs.html +147 -147
  105. package/web-ui/partials/index/panel-market.html +177 -177
  106. package/web-ui/partials/index/panel-orchestration.html +391 -391
  107. package/web-ui/partials/index/panel-plugins.html +253 -279
  108. package/web-ui/partials/index/panel-sessions.html +316 -326
  109. package/web-ui/partials/index/panel-settings.html +253 -274
  110. package/web-ui/partials/index/panel-usage.html +371 -371
  111. package/web-ui/res/json5.min.js +1 -1
  112. package/web-ui/res/vue.global.prod.js +13 -13
  113. package/web-ui/session-helpers.mjs +576 -576
  114. package/web-ui/source-bundle.cjs +233 -233
  115. package/web-ui/styles/base-theme.css +281 -268
  116. package/web-ui/styles/controls-forms.css +422 -423
  117. package/web-ui/styles/dashboard.css +274 -274
  118. package/web-ui/styles/docs-panel.css +247 -247
  119. package/web-ui/styles/feedback.css +108 -108
  120. package/web-ui/styles/health-check-dialog.css +144 -144
  121. package/web-ui/styles/layout-shell.css +606 -603
  122. package/web-ui/styles/modals-core.css +466 -464
  123. package/web-ui/styles/navigation-panels.css +391 -390
  124. package/web-ui/styles/openclaw-structured.css +266 -266
  125. package/web-ui/styles/plugins-panel.css +523 -523
  126. package/web-ui/styles/responsive.css +454 -454
  127. package/web-ui/styles/sessions-list.css +419 -415
  128. package/web-ui/styles/sessions-preview.css +411 -411
  129. package/web-ui/styles/sessions-toolbar-trash.css +330 -330
  130. package/web-ui/styles/sessions-usage.css +1040 -1040
  131. package/web-ui/styles/settings-panel.css +185 -185
  132. package/web-ui/styles/skills-list.css +303 -303
  133. package/web-ui/styles/skills-market.css +406 -406
  134. package/web-ui/styles/task-orchestration.css +822 -822
  135. package/web-ui/styles/titles-cards.css +472 -408
  136. package/web-ui/styles.css +21 -21
  137. package/web-ui.html +17 -17
@@ -1,765 +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
- 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
- }
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
+ }