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