lumencode 1.3.2 → 1.3.3
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/lib/attribution.js +8 -0
- package/lib/git.js +195 -192
- package/lib/report.js +5 -1
- package/package.json +1 -1
- package/public/app.js +1170 -1167
package/public/app.js
CHANGED
|
@@ -1,1167 +1,1170 @@
|
|
|
1
|
-
import { COLORS, SCENARIO_COLORS, TEXT, ID, STORAGE } from './config.js';
|
|
2
|
-
import { esc, fmt, fmtShort, destroyChart, destroyAllCharts, getChart, setChart, todayISO, fmtDate, TOOL_DISPLAY_NAMES, groupMcpByServer, aggregateToolsWithDualCounts } from './utils.js';
|
|
3
|
-
import { createLatestRequestGuard, fetchTools, fetchReport, fetchConfig, saveConfig, fetchDetails, fetchSessions, fetchStepStats, fetchHooksStatus, updateHooks } from './api.js';
|
|
4
|
-
import { renderWorkTypePie, renderModelBars, renderProjectBars, renderTimelineArea, renderCacheStack } from './charts.js';
|
|
5
|
-
import { renderGitInsights, renderLineBlameEvidence } from './git-insights.js';
|
|
6
|
-
import { loadWorkReport, copyWorkReport, downloadMarkdown, getWorkReportState, setWorkReportState } from './work-report.js';
|
|
7
|
-
import { exportCSV, printReport, exportJSON, exportHTML } from './export.js';
|
|
8
|
-
|
|
9
|
-
/* ── Alpine App Component ── */
|
|
10
|
-
function appState() {
|
|
11
|
-
return {
|
|
12
|
-
/* state */
|
|
13
|
-
view: 'ledger',
|
|
14
|
-
period: 'daily',
|
|
15
|
-
activeTool: 'all',
|
|
16
|
-
railCollapsed: localStorage.getItem(STORAGE.SIDEBAR_COLLAPSED) === 'true',
|
|
17
|
-
theme: localStorage.getItem(STORAGE.THEME) || 'dark',
|
|
18
|
-
currentDate: todayISO(),
|
|
19
|
-
today: todayISO(),
|
|
20
|
-
loading: false,
|
|
21
|
-
error: null,
|
|
22
|
-
hasData: false,
|
|
23
|
-
availableTools: [],
|
|
24
|
-
appName: 'LumenCode',
|
|
25
|
-
appVersion: '',
|
|
26
|
-
lastReportData: null,
|
|
27
|
-
cache: {},
|
|
28
|
-
_cacheOrder: [],
|
|
29
|
-
_cacheMaxSize: 30,
|
|
30
|
-
reportRequestGuard: createLatestRequestGuard(),
|
|
31
|
-
|
|
32
|
-
/* report view state */
|
|
33
|
-
reportLevel: 'detailed',
|
|
34
|
-
reportPlatform: 'default',
|
|
35
|
-
reportProject: '',
|
|
36
|
-
reportProjects: [],
|
|
37
|
-
copied: false,
|
|
38
|
-
reportHtml: '',
|
|
39
|
-
|
|
40
|
-
/* constants */
|
|
41
|
-
customStart: '',
|
|
42
|
-
customEnd: '',
|
|
43
|
-
periods: [
|
|
44
|
-
{ id: 'daily', cn: '日', en: 'DAY' },
|
|
45
|
-
{ id: 'weekly', cn: '周', en: 'WEEK' },
|
|
46
|
-
{ id: 'monthly', cn: '月', en: 'MONTH' },
|
|
47
|
-
{ id: 'custom', cn: '自定义', en: 'CUSTOM' },
|
|
48
|
-
],
|
|
49
|
-
colors: {
|
|
50
|
-
rust: 'var(--rust)', dest: 'var(--dest)', forest: 'var(--forest)',
|
|
51
|
-
ochre: 'var(--ochre)', clay: 'var(--clay)',
|
|
52
|
-
},
|
|
53
|
-
toolColors: { claude: 'var(--claude)', codex: 'var(--codex)', opencode: 'var(--opencode)' },
|
|
54
|
-
toolSubNames: { claude: 'ANTHROPIC', codex: 'OPENAI', opencode: 'OSS' },
|
|
55
|
-
|
|
56
|
-
/* computed getters */
|
|
57
|
-
get periodMeta() { return this.periods.find(p => p.id === this.period) || this.periods[0]; },
|
|
58
|
-
get dateDisplay() {
|
|
59
|
-
if (this.period === 'custom') {
|
|
60
|
-
if (this.customStart && this.customEnd) return `${this.customStart.replace(/-/g, '.')} — ${this.customEnd.replace(/-/g, '.')}`;
|
|
61
|
-
return '选择日期范围';
|
|
62
|
-
}
|
|
63
|
-
if (this.period === 'daily') return this.currentDate.replace(/-/g, '.');
|
|
64
|
-
if (this.period === 'weekly') {
|
|
65
|
-
const d = new Date(this.currentDate);
|
|
66
|
-
const start = new Date(d); start.setDate(d.getDate() - d.getDay() + 1);
|
|
67
|
-
const end = new Date(start); end.setDate(start.getDate() + 6);
|
|
68
|
-
return `${fmtDate(start)} — ${fmtDate(end)}`;
|
|
69
|
-
}
|
|
70
|
-
return this.currentDate.slice(0, 7).replace('-', '.');
|
|
71
|
-
},
|
|
72
|
-
get generatedAt() { return fmtDate(new Date()) + ' · ' + new Date().toLocaleTimeString('zh-CN', {hour:'2-digit',minute:'2-digit'}) + ' UTC+8'; },
|
|
73
|
-
get traceId() { return 'CT-' + this.currentDate.replace(/-/g, '-'); },
|
|
74
|
-
|
|
75
|
-
/* KPI defaults */
|
|
76
|
-
kpiData: [
|
|
77
|
-
{ label: '活跃天数', sub: 'ACTIVE DAYS', value: '-', unit: '/ 31', delta: '', trend: 'flat' },
|
|
78
|
-
{ label: '覆盖项目', sub: 'PROJECTS', value: '-', unit: '个', delta: '', trend: 'flat' },
|
|
79
|
-
{ label: '高峰天数', sub: 'PEAK DAYS', value: '-', unit: '天', delta: '', trend: 'flat' },
|
|
80
|
-
{ label: 'Token 消耗 · 含缓存', sub: 'TOKENS · INC. CACHE', value: '-', unit: 'M', delta: '', trend: 'flat' },
|
|
81
|
-
{ label: '估算成本', sub: 'EST. COST USD', value: '-', unit: '', delta: '', trend: 'flat' },
|
|
82
|
-
],
|
|
83
|
-
|
|
84
|
-
/* AI contribution defaults */
|
|
85
|
-
aiLinePct: 0,
|
|
86
|
-
aiLinePctDisplay: 0,
|
|
87
|
-
_aiPctAnim: null,
|
|
88
|
-
aiSummaryDesc: '',
|
|
89
|
-
attributionPct: '0% / 100%',
|
|
90
|
-
confirmedPct: 0,
|
|
91
|
-
inferredPct: 0,
|
|
92
|
-
unattribPct: 0,
|
|
93
|
-
sourceClaudePct: 0,
|
|
94
|
-
sourceCodexPct: 0,
|
|
95
|
-
sourceOpencodePct: 0,
|
|
96
|
-
sourceBreakdown: [],
|
|
97
|
-
aiContributionMeta: '- / - LINES',
|
|
98
|
-
lineBlameEvidence: null,
|
|
99
|
-
lineBlamePrecision: '',
|
|
100
|
-
stepStats: null,
|
|
101
|
-
stepStatusLabel: '',
|
|
102
|
-
hooksStatus: null,
|
|
103
|
-
hooksBusy: false,
|
|
104
|
-
gitOutputCells: [
|
|
105
|
-
{ l: '提交', en: 'COMMITS', v: '-', c: '' },
|
|
106
|
-
{ l: '变更文件', en: 'FILES', v: '-', c: '' },
|
|
107
|
-
{ l: '新增', en: '+ ADDED', v: '-', c: 'var(--forest)' },
|
|
108
|
-
{ l: '删除', en: '− REMOVED', v: '-', c: 'var(--dest)' },
|
|
109
|
-
],
|
|
110
|
-
attributionCells: [
|
|
111
|
-
{ l: 'AI 改写', en: 'REWRITE', v: '-', c: '' },
|
|
112
|
-
{ l: 'AI 提交', en: 'COMMITS', v: '-', c: 'var(--forest)' },
|
|
113
|
-
{ l: '可能上限', en: 'MAX', v: '-', c: '' },
|
|
114
|
-
{ l: '高·中置信', en: 'HI · MID', v: '-', c: 'var(--ochre)' },
|
|
115
|
-
{ l: 'AI 新增', en: '+ AI', v: '-', c: 'var(--forest)' },
|
|
116
|
-
{ l: 'AI 删除', en: '− AI', v: '-', c: 'var(--dest)' },
|
|
117
|
-
],
|
|
118
|
-
|
|
119
|
-
/* section data defaults */
|
|
120
|
-
editTypeData: [],
|
|
121
|
-
topFilesData: [],
|
|
122
|
-
topFilesMeta: '+0 / −0',
|
|
123
|
-
workTypeData: [],
|
|
124
|
-
modelData: [],
|
|
125
|
-
topModelName: '-',
|
|
126
|
-
activeModels: '-',
|
|
127
|
-
cacheHitRate: 0,
|
|
128
|
-
cacheDelta: '',
|
|
129
|
-
cacheData: [],
|
|
130
|
-
cacheSavingText: '',
|
|
131
|
-
timelineMeta: [
|
|
132
|
-
{ l: 'PEAK DAY', v: '-', s: '-' },
|
|
133
|
-
{ l: 'AVG / DAY', v: '-', s: 'sessions' },
|
|
134
|
-
{ l: 'LONGEST STREAK', v: '-', s: 'consecutive days' },
|
|
135
|
-
{ l: 'IDLE DAYS', v: '-', s: 'no activity' },
|
|
136
|
-
],
|
|
137
|
-
toolRankData: [],
|
|
138
|
-
toolRankTotal: 0,
|
|
139
|
-
toolRankTab: 'all',
|
|
140
|
-
toolRankTotalCalls: 0,
|
|
141
|
-
toolRankAllTotal: 0,
|
|
142
|
-
toolRankSkillTotal: 0,
|
|
143
|
-
toolRankMcpTotal: 0,
|
|
144
|
-
projectData: [],
|
|
145
|
-
|
|
146
|
-
/* tool summary for rail */
|
|
147
|
-
toolTokens: { all: '-' },
|
|
148
|
-
toolSessions: { all: 0 },
|
|
149
|
-
|
|
150
|
-
/* report view data */
|
|
151
|
-
reportKpis: [
|
|
152
|
-
{ l: 'TOKENS', v: '-', s: '估算成本 -', accent: false },
|
|
153
|
-
{ l: 'COMMITS', v: '-', s: '- / - 行', accent: false },
|
|
154
|
-
{ l: 'AI CONTRIBUTION', v: '-', s: '- 行可独立运行', accent: true },
|
|
155
|
-
{ l: 'ACTIVE DAYS', v: '-', s: '连续 - 天最长', accent: false },
|
|
156
|
-
],
|
|
157
|
-
reportSubTitle: '',
|
|
158
|
-
reportSummary: '',
|
|
159
|
-
reportHighlights: [],
|
|
160
|
-
|
|
161
|
-
get hooksNeedAction() {
|
|
162
|
-
if (!this.hooksStatus) return false;
|
|
163
|
-
return !this.hooksStatus.stepsInitialized ||
|
|
164
|
-
!this.hooksStatus.claude?.enabled ||
|
|
165
|
-
!this.hooksStatus.codex?.enabled ||
|
|
166
|
-
!this.hooksStatus.opencode?.enabled;
|
|
167
|
-
},
|
|
168
|
-
|
|
169
|
-
get hooksStatusText() {
|
|
170
|
-
if (!this.hooksStatus) return '正在检查 hooks 状态';
|
|
171
|
-
const total = this.hooksStatus.projectCount ?? this.hooksStatus.claude?.total ?? 0;
|
|
172
|
-
if (this.hooksStatus.targetMode === 'configured-projects') {
|
|
173
|
-
if (total === 0) return '未配置项目,请先在设置中添加项目路径';
|
|
174
|
-
const parts = [
|
|
175
|
-
`Claude ${this.hooksStatus.claude?.enabledCount || 0}/${total}`,
|
|
176
|
-
`Codex ${this.hooksStatus.codex?.enabledCount || 0}/${total}`,
|
|
177
|
-
`OpenCode ${this.hooksStatus.opencode?.enabledCount || 0}/${total}`,
|
|
178
|
-
`steps ${this.hooksStatus.stepsReadyCount || 0}/${total}`,
|
|
179
|
-
];
|
|
180
|
-
return `设置内项目 hooks:${parts.join(' / ')}`;
|
|
181
|
-
}
|
|
182
|
-
const parts = [
|
|
183
|
-
`Claude ${this.hooksStatus.claude?.enabled ? '已开启' : '未开启'}`,
|
|
184
|
-
`Codex ${this.hooksStatus.codex?.enabled ? '已开启' : '未开启'}`,
|
|
185
|
-
`OpenCode ${this.hooksStatus.opencode?.enabled ? '已开启' : '未开启'}`,
|
|
186
|
-
`steps ${this.hooksStatus.stepsInitialized ? '已初始化' : '未初始化'}`,
|
|
187
|
-
];
|
|
188
|
-
return parts.join(' / ');
|
|
189
|
-
},
|
|
190
|
-
|
|
191
|
-
/* ── init ── */
|
|
192
|
-
async init() {
|
|
193
|
-
this.loadStateFromHash();
|
|
194
|
-
if (this.theme === 'dark') document.documentElement.classList.add('dark');
|
|
195
|
-
else document.documentElement.classList.remove('dark');
|
|
196
|
-
this.$watch('view', (value) => {
|
|
197
|
-
if (value === 'ledger' && this.lastReportData) {
|
|
198
|
-
this.$nextTick(() => this.renderCharts(this.lastReportData));
|
|
199
|
-
}
|
|
200
|
-
});
|
|
201
|
-
await this.loadTools();
|
|
202
|
-
await this.loadHooksStatus();
|
|
203
|
-
await this.loadStepStats();
|
|
204
|
-
// 首次加载时先获取全量数据填充侧边栏,再按当前工具加载
|
|
205
|
-
if (this.activeTool !== 'all') {
|
|
206
|
-
try {
|
|
207
|
-
const allData = await fetchReport({ tool: 'all', period: this.period, date: this.currentDate });
|
|
208
|
-
if (allData && !allData.error) {
|
|
209
|
-
this.computeToolTokens(allData.usageStats, allData.toolBreakdown);
|
|
210
|
-
}
|
|
211
|
-
} catch {}
|
|
212
|
-
}
|
|
213
|
-
await this.loadCurrentView();
|
|
214
|
-
},
|
|
215
|
-
|
|
216
|
-
/* ── theme ── */
|
|
217
|
-
toggleTheme() {
|
|
218
|
-
this.theme = this.theme === 'dark' ? 'light' : 'dark';
|
|
219
|
-
localStorage.setItem(STORAGE.THEME, this.theme);
|
|
220
|
-
if (this.theme === 'dark') document.documentElement.classList.add('dark');
|
|
221
|
-
else document.documentElement.classList.remove('dark');
|
|
222
|
-
/* re-render charts to pick up new colors */
|
|
223
|
-
if (this.lastReportData && this.view === 'ledger') this.renderCharts(this.lastReportData);
|
|
224
|
-
},
|
|
225
|
-
|
|
226
|
-
/* ── tools ── */
|
|
227
|
-
async loadTools() {
|
|
228
|
-
try {
|
|
229
|
-
const data = await fetchTools();
|
|
230
|
-
this.availableTools = data.tools || data || [];
|
|
231
|
-
if (data.appName) this.appName = data.appName;
|
|
232
|
-
if (data.appVersion) this.appVersion = data.appVersion;
|
|
233
|
-
} catch (e) { console.warn('loadTools failed:', e); this.availableTools = []; }
|
|
234
|
-
},
|
|
235
|
-
|
|
236
|
-
async loadStepStats() {
|
|
237
|
-
try {
|
|
238
|
-
const data = await fetchStepStats();
|
|
239
|
-
this.stepStats = data;
|
|
240
|
-
this.stepStatusLabel = data?.available
|
|
241
|
-
? `STEP READY · ${data.stepCount || 0}`
|
|
242
|
-
: 'STEP NOT READY';
|
|
243
|
-
} catch {
|
|
244
|
-
this.stepStats = null;
|
|
245
|
-
this.stepStatusLabel = '';
|
|
246
|
-
}
|
|
247
|
-
},
|
|
248
|
-
|
|
249
|
-
async loadHooksStatus() {
|
|
250
|
-
try {
|
|
251
|
-
this.hooksStatus = await fetchHooksStatus();
|
|
252
|
-
} catch (e) {
|
|
253
|
-
console.warn('loadHooksStatus failed:', e);
|
|
254
|
-
this.hooksStatus = null;
|
|
255
|
-
}
|
|
256
|
-
},
|
|
257
|
-
|
|
258
|
-
showHooksConfirmModal() {
|
|
259
|
-
const count = this.hooksStatus?.projectCount ?? 0;
|
|
260
|
-
const el = document.getElementById('hooksConfirmCount');
|
|
261
|
-
if (el) el.textContent = count;
|
|
262
|
-
const modal = document.getElementById('hooksConfirmModal');
|
|
263
|
-
if (modal) modal.style.display = 'flex';
|
|
264
|
-
},
|
|
265
|
-
|
|
266
|
-
hideHooksConfirmModal() {
|
|
267
|
-
const modal = document.getElementById('hooksConfirmModal');
|
|
268
|
-
if (modal) modal.style.display = 'none';
|
|
269
|
-
},
|
|
270
|
-
|
|
271
|
-
async enableHooksFromUi() {
|
|
272
|
-
this.hideHooksConfirmModal();
|
|
273
|
-
if (this.hooksBusy) return;
|
|
274
|
-
this.hooksBusy = true;
|
|
275
|
-
try {
|
|
276
|
-
await updateHooks('enable');
|
|
277
|
-
await this.loadHooksStatus();
|
|
278
|
-
await this.loadStepStats();
|
|
279
|
-
showToast('hooks 已开启');
|
|
280
|
-
} catch (err) {
|
|
281
|
-
showToast('开启 hooks 失败: ' + err.message);
|
|
282
|
-
} finally {
|
|
283
|
-
this.hooksBusy = false;
|
|
284
|
-
}
|
|
285
|
-
},
|
|
286
|
-
|
|
287
|
-
showHooksDisableConfirmModal() {
|
|
288
|
-
const modal = document.getElementById('hooksDisableConfirmModal');
|
|
289
|
-
if (modal) modal.style.display = 'flex';
|
|
290
|
-
},
|
|
291
|
-
|
|
292
|
-
hideHooksDisableConfirmModal() {
|
|
293
|
-
const modal = document.getElementById('hooksDisableConfirmModal');
|
|
294
|
-
if (modal) modal.style.display = 'none';
|
|
295
|
-
},
|
|
296
|
-
|
|
297
|
-
async disableHooksFromUi() {
|
|
298
|
-
this.hideHooksDisableConfirmModal();
|
|
299
|
-
if (this.hooksBusy) return;
|
|
300
|
-
this.hooksBusy = true;
|
|
301
|
-
try {
|
|
302
|
-
await updateHooks('disable');
|
|
303
|
-
await this.loadHooksStatus();
|
|
304
|
-
await this.loadStepStats();
|
|
305
|
-
showToast('hooks 已关闭');
|
|
306
|
-
} catch (err) {
|
|
307
|
-
showToast('关闭 hooks 失败: ' + err.message);
|
|
308
|
-
} finally {
|
|
309
|
-
this.hooksBusy = false;
|
|
310
|
-
}
|
|
311
|
-
},
|
|
312
|
-
|
|
313
|
-
setTool(name) {
|
|
314
|
-
this.activeTool = name;
|
|
315
|
-
this.loadCurrentView();
|
|
316
|
-
if (this.view === 'report') this.loadReportContent();
|
|
317
|
-
},
|
|
318
|
-
|
|
319
|
-
setToolRankTab(tab) {
|
|
320
|
-
this.toolRankTab = tab;
|
|
321
|
-
this._computeToolRank();
|
|
322
|
-
const container = document.getElementById('toolCallsContainer');
|
|
323
|
-
if (container) container.scrollTop = 0;
|
|
324
|
-
},
|
|
325
|
-
|
|
326
|
-
_computeToolRank() {
|
|
327
|
-
const usageStats = this._lastUsageStats || {};
|
|
328
|
-
const tab = this.toolRankTab;
|
|
329
|
-
const getCalls = (val) => typeof val === 'number' ? val : (val.calls || 0);
|
|
330
|
-
const getUses = (val) => typeof val === 'number' ? val : (val.uses || 0);
|
|
331
|
-
const sumCalls = (obj) => Object.values(obj || {}).reduce((s, v) => s + getCalls(v), 0);
|
|
332
|
-
|
|
333
|
-
this.toolRankAllTotal = sumCalls(usageStats.tools);
|
|
334
|
-
this.toolRankSkillTotal = sumCalls(usageStats.skills);
|
|
335
|
-
this.toolRankMcpTotal = sumCalls(usageStats.mcpTools);
|
|
336
|
-
|
|
337
|
-
if (tab === 'all') {
|
|
338
|
-
const dual = aggregateToolsWithDualCounts(usageStats.tools || {});
|
|
339
|
-
const entries = Object.entries(dual).sort((a, b) => b[1].uses - a[1].uses);
|
|
340
|
-
const maxUses = Math.max(...entries.map(([, v]) => v.uses), 1);
|
|
341
|
-
this.toolRankData = entries.map(([name, d]) => ({
|
|
342
|
-
name,
|
|
343
|
-
calls: d.calls,
|
|
344
|
-
uses: d.uses,
|
|
345
|
-
value: d.calls,
|
|
346
|
-
pct: Math.round((d.uses / maxUses) * 100),
|
|
347
|
-
displayName: TOOL_DISPLAY_NAMES[name] || '',
|
|
348
|
-
}));
|
|
349
|
-
this.toolRankTotalCalls = this.toolRankAllTotal;
|
|
350
|
-
} else if (tab === 'skill') {
|
|
351
|
-
const skills = usageStats.skills || {};
|
|
352
|
-
const entries = Object.entries(skills).sort((a, b) => getUses(b[1]) - getUses(a[1]));
|
|
353
|
-
const maxUses = Math.max(...entries.map(([, v]) => getUses(v)), 1);
|
|
354
|
-
this.toolRankData = entries.map(([name, val]) => {
|
|
355
|
-
const calls = getCalls(val);
|
|
356
|
-
const uses = getUses(val);
|
|
357
|
-
return {
|
|
358
|
-
name,
|
|
359
|
-
calls,
|
|
360
|
-
uses,
|
|
361
|
-
value: calls,
|
|
362
|
-
pct: Math.round((uses / maxUses) * 100),
|
|
363
|
-
displayName: '',
|
|
364
|
-
};
|
|
365
|
-
});
|
|
366
|
-
this.toolRankTotalCalls = this.toolRankSkillTotal;
|
|
367
|
-
} else if (tab === 'mcp') {
|
|
368
|
-
this.toolRankData = groupMcpByServer(usageStats.mcpTools || {});
|
|
369
|
-
this.toolRankTotalCalls = this.toolRankMcpTotal;
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
this.toolRankTotal = this.toolRankData.length;
|
|
373
|
-
let rank = 0;
|
|
374
|
-
for (const item of this.toolRankData) {
|
|
375
|
-
if (!item.isGroup) item.rank = ++rank;
|
|
376
|
-
}
|
|
377
|
-
},
|
|
378
|
-
|
|
379
|
-
/* ── period / date ── */
|
|
380
|
-
setPeriod(p) {
|
|
381
|
-
this.period = p;
|
|
382
|
-
if (p !== 'custom') {
|
|
383
|
-
this.customStart = '';
|
|
384
|
-
this.customEnd = '';
|
|
385
|
-
this.saveStateToHash();
|
|
386
|
-
this.loadCurrentView();
|
|
387
|
-
if (this.view === 'report') this.loadReportContent();
|
|
388
|
-
}
|
|
389
|
-
},
|
|
390
|
-
|
|
391
|
-
onCustomStartChange() {
|
|
392
|
-
if (this.customStart && this.customEnd) {
|
|
393
|
-
this.loadCurrentView();
|
|
394
|
-
if (this.view === 'report') this.loadReportContent();
|
|
395
|
-
}
|
|
396
|
-
},
|
|
397
|
-
|
|
398
|
-
onCustomEndChange() {
|
|
399
|
-
if (this.customStart && this.customEnd) {
|
|
400
|
-
this.loadCurrentView();
|
|
401
|
-
if (this.view === 'report') this.loadReportContent();
|
|
402
|
-
}
|
|
403
|
-
},
|
|
404
|
-
|
|
405
|
-
shiftDate(dir) {
|
|
406
|
-
const d = new Date(this.currentDate);
|
|
407
|
-
if (this.period === 'monthly') {
|
|
408
|
-
d.setMonth(d.getMonth() + dir);
|
|
409
|
-
} else {
|
|
410
|
-
const step = this.period === 'weekly' ? 7 * dir : dir;
|
|
411
|
-
d.setDate(d.getDate() + step);
|
|
412
|
-
}
|
|
413
|
-
this.currentDate = d.toISOString().slice(0, 10);
|
|
414
|
-
this.saveStateToHash();
|
|
415
|
-
this.loadCurrentView();
|
|
416
|
-
if (this.view === 'report') this.loadReportContent();
|
|
417
|
-
},
|
|
418
|
-
|
|
419
|
-
onDateChange() {
|
|
420
|
-
if (this.currentDate > this.today) this.currentDate = this.today;
|
|
421
|
-
this.saveStateToHash();
|
|
422
|
-
this.loadCurrentView();
|
|
423
|
-
if (this.view === 'report') this.loadReportContent();
|
|
424
|
-
},
|
|
425
|
-
|
|
426
|
-
loadStateFromHash() {
|
|
427
|
-
const hash = location.hash.slice(1);
|
|
428
|
-
if (!hash) return;
|
|
429
|
-
const [p, d] = hash.split('/');
|
|
430
|
-
if (p && ['daily', 'weekly', 'monthly', 'custom'].includes(p)) this.period = p;
|
|
431
|
-
if (d && /^\d{4}-\d{2}-\d{2}$/.test(d)) this.currentDate = d;
|
|
432
|
-
},
|
|
433
|
-
|
|
434
|
-
saveStateToHash() {
|
|
435
|
-
location.hash = `${this.period}/${this.currentDate}`;
|
|
436
|
-
},
|
|
437
|
-
|
|
438
|
-
/* ── data loading ── */
|
|
439
|
-
async loadCurrentView() {
|
|
440
|
-
const cacheKey = `${this.activeTool}-${this.period}-${this.period === 'custom' ? this.customStart + '~' + this.customEnd : this.currentDate}`;
|
|
441
|
-
const request = this.reportRequestGuard.next();
|
|
442
|
-
|
|
443
|
-
if (this.cache[cacheKey]) {
|
|
444
|
-
const idx = this._cacheOrder.indexOf(cacheKey);
|
|
445
|
-
if (idx !== -1) { this._cacheOrder.splice(idx, 1); this._cacheOrder.push(cacheKey); }
|
|
446
|
-
this.renderData(this.cache[cacheKey]);
|
|
447
|
-
this.loading = false;
|
|
448
|
-
return;
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
this.loading = true;
|
|
452
|
-
this.error = null;
|
|
453
|
-
|
|
454
|
-
try {
|
|
455
|
-
const params = { tool: this.activeTool, period: this.period, date: this.currentDate };
|
|
456
|
-
if (this.period === 'custom' && this.customStart && this.customEnd) {
|
|
457
|
-
params.start = this.customStart;
|
|
458
|
-
params.end = this.customEnd;
|
|
459
|
-
}
|
|
460
|
-
const data = await fetchReport(params, request.signal);
|
|
461
|
-
if (!request.isCurrent()) return;
|
|
462
|
-
|
|
463
|
-
if (!data || data.error) {
|
|
464
|
-
this.hasData = false;
|
|
465
|
-
if (data?.error === TEXT.NOT_CONFIGURED) {
|
|
466
|
-
this.showWelcome();
|
|
467
|
-
}
|
|
468
|
-
return;
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
this.hideWelcome();
|
|
472
|
-
this.cache[cacheKey] = data;
|
|
473
|
-
this._cacheOrder.push(cacheKey);
|
|
474
|
-
while (this._cacheOrder.length > this._cacheMaxSize) {
|
|
475
|
-
const old = this._cacheOrder.shift();
|
|
476
|
-
delete this.cache[old];
|
|
477
|
-
}
|
|
478
|
-
this.lastReportData = data;
|
|
479
|
-
this.renderData(data);
|
|
480
|
-
} catch (err) {
|
|
481
|
-
if (err.name === 'AbortError') return;
|
|
482
|
-
this.error = err.message;
|
|
483
|
-
showToast('加载失败: ' + err.message);
|
|
484
|
-
} finally {
|
|
485
|
-
if (request.isCurrent()) this.loading = false;
|
|
486
|
-
}
|
|
487
|
-
},
|
|
488
|
-
|
|
489
|
-
showWelcome() {
|
|
490
|
-
const wp = document.getElementById(ID.WELCOME_PAGE);
|
|
491
|
-
if (wp) wp.style.display = 'flex';
|
|
492
|
-
},
|
|
493
|
-
|
|
494
|
-
hideWelcome() {
|
|
495
|
-
const wp = document.getElementById(ID.WELCOME_PAGE);
|
|
496
|
-
if (wp) wp.style.display = 'none';
|
|
497
|
-
},
|
|
498
|
-
|
|
499
|
-
/* ── render data ── */
|
|
500
|
-
renderData(data) {
|
|
501
|
-
const { usageStats, gitStats, start, end, prevStats, trendData, costBreakdown } = data;
|
|
502
|
-
this._lastUsageStats = usageStats;
|
|
503
|
-
this.hasData = usageStats.requestCount > 0;
|
|
504
|
-
if (!this.hasData) {
|
|
505
|
-
this.kpiData = [
|
|
506
|
-
{ label: '活跃天数', sub: 'ACTIVE DAYS', value: '-', unit: '/ ' + (this.period === 'daily' ? '1' : this.period === 'weekly' ? '7' : '31'), delta: '', trend: 'flat' },
|
|
507
|
-
{ label: '覆盖项目', sub: 'PROJECTS', value: '0', unit: '个', delta: '', trend: 'flat' },
|
|
508
|
-
{ label: '高峰天数', sub: 'PEAK DAYS', value: '-', unit: '天', delta: '', trend: 'flat' },
|
|
509
|
-
{ label: 'Token 消耗 · 含缓存', sub: 'TOKENS · INC. CACHE', value: '0.00', unit: 'M', delta: '', trend: 'flat' },
|
|
510
|
-
{ label: '估算成本', sub: 'EST. COST USD', value: '$0.00', unit: '', delta: '', trend: 'flat' },
|
|
511
|
-
];
|
|
512
|
-
destroyAllCharts(['workTypeChart', 'modelChart', 'projectChart', 'toolChart', 'timelineChart', 'commitTypeChart', 'cacheChart']);
|
|
513
|
-
return;
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
/* KPI strip */
|
|
517
|
-
const days = Object.keys(usageStats.dailyStats || {}).length || 1;
|
|
518
|
-
const totalMin = Math.round((usageStats.requestCount || 0) * 2.4);
|
|
519
|
-
const peakDay = Object.entries(usageStats.dailyStats || {}).sort((a, b) => (b[1].requests || 0) - (a[1].requests || 0))[0];
|
|
520
|
-
const tokensM = (usageStats.totalTokens / 1_000_000).toFixed(2);
|
|
521
|
-
const cost = usageStats.estimatedCost || 0;
|
|
522
|
-
const prevCost = prevStats?.estimatedCost || 0;
|
|
523
|
-
const costDelta = prevCost > 0 ? ((cost - prevCost) / prevCost * 100).toFixed(1) : 0;
|
|
524
|
-
const costTrend = cost > prevCost ? 'up' : cost < prevCost ? 'down' : 'flat';
|
|
525
|
-
|
|
526
|
-
this.kpiData = [
|
|
527
|
-
{ label: '活跃天数', sub: 'ACTIVE DAYS', value: String(days), unit: '/ ' + (this.period === 'daily' ? '1' : this.period === 'weekly' ? '7' : '31'), delta: '', trend: 'flat' },
|
|
528
|
-
{ label: '覆盖项目', sub: 'PROJECTS', value: String(Object.keys(usageStats.projects || {}).length), unit: '个', delta: '', trend: 'flat' },
|
|
529
|
-
{ label: '高峰天数', sub: 'PEAK DAYS', value: peakDay ? peakDay[0].slice(5) : '-', unit: '天', delta: '', trend: 'flat' },
|
|
530
|
-
{ label: 'Token 消耗 · 含缓存', sub: 'TOKENS · INC. CACHE', value: tokensM, unit: 'M', delta: '', trend: 'flat' },
|
|
531
|
-
{ label: '估算成本', sub: 'EST. COST USD', value: '$' + cost.toFixed(2), unit: '', delta: (costDelta > 0 ? '+' : '') + costDelta + '%', trend: costTrend },
|
|
532
|
-
];
|
|
533
|
-
|
|
534
|
-
/* AI contribution */
|
|
535
|
-
this.renderAIContribution(gitStats, usageStats);
|
|
536
|
-
|
|
537
|
-
/* Edit types (commit types) */
|
|
538
|
-
const typeEntries = gitStats?.commitTypes ? Object.entries(gitStats.commitTypes).filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]) : [];
|
|
539
|
-
const maxType = Math.max(...typeEntries.map(([, v]) => v), 1);
|
|
540
|
-
const inkSteps = ['var(--rust)', 'var(--ink-82)', 'var(--ink-62)', 'var(--ink-46)', 'var(--ink-32)', 'var(--ink-22)'];
|
|
541
|
-
this.editTypeData = typeEntries.map(([name, value], idx) => ({
|
|
542
|
-
name, value, pct: Math.round((value / maxType) * 100),
|
|
543
|
-
color: inkSteps[Math.min(idx, inkSteps.length - 1)],
|
|
544
|
-
}));
|
|
545
|
-
|
|
546
|
-
/* Top files */
|
|
547
|
-
const hotspots = gitStats?.fileHotspots || [];
|
|
548
|
-
this.topFilesData = hotspots.slice(0, 10).map(h => ({ path: h.path, commits: h.touches, plus: h.added, minus: h.deleted }));
|
|
549
|
-
const totalAdded = hotspots.reduce((s, h) => s + (h.added || 0), 0);
|
|
550
|
-
const totalDeleted = hotspots.reduce((s, h) => s + (h.deleted || 0), 0);
|
|
551
|
-
this.topFilesMeta = `+${fmt(totalAdded)} / −${fmt(totalDeleted)}`;
|
|
552
|
-
|
|
553
|
-
/* Work type (scenarios) */
|
|
554
|
-
const scenarioEntries = Object.entries(usageStats.scenarios || {}).filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]);
|
|
555
|
-
const totalScenario = scenarioEntries.reduce((s, [, v]) => s + v, 0) || 1;
|
|
556
|
-
this.workTypeData = scenarioEntries.map(([name, value], i) => ({
|
|
557
|
-
name, value: Math.round((value / totalScenario) * 100),
|
|
558
|
-
color: SCENARIO_COLORS[name] || '#888',
|
|
559
|
-
hidden: false,
|
|
560
|
-
}));
|
|
561
|
-
|
|
562
|
-
/* Models */
|
|
563
|
-
const modelEntries = Object.entries(usageStats.models || {}).sort((a, b) => b[1].count - a[1].count);
|
|
564
|
-
const maxModel = Math.max(...modelEntries.map(([, v]) => v.count), 1);
|
|
565
|
-
const totalModelReq = modelEntries.reduce((s, [, v]) => s + v.count, 0) || 1;
|
|
566
|
-
this.modelData = modelEntries.map(([name, d]) => ({
|
|
567
|
-
name, pct: Math.round((d.count / totalModelReq) * 100),
|
|
568
|
-
barPct: Math.round((d.count / maxModel) * 100),
|
|
569
|
-
}));
|
|
570
|
-
this.topModelName = modelEntries[0]?.[0] || '-';
|
|
571
|
-
this.activeModels = `${modelEntries.length} / 12`;
|
|
572
|
-
|
|
573
|
-
/* Cache */
|
|
574
|
-
const cacheRead = usageStats.cacheRead || 0;
|
|
575
|
-
const cacheCreate = usageStats.cacheCreate || 0;
|
|
576
|
-
const inputTok = usageStats.inputTokens || 1;
|
|
577
|
-
const cacheTotal = cacheRead + cacheCreate + inputTok;
|
|
578
|
-
this.cacheHitRate = cacheTotal > 0 ? Math.round((cacheRead / cacheTotal) * 100) : 0;
|
|
579
|
-
this.cacheDelta = cacheRead > 0 ? '+17pp' : '';
|
|
580
|
-
this.cacheData = [
|
|
581
|
-
{ label: '命中', en: 'HIT', value: this.cacheHitRate, color: 'var(--forest)' },
|
|
582
|
-
{ label: '未命中', en: 'MISS', value: cacheTotal > 0 ? Math.round((inputTok / cacheTotal) * 100) : 0, color: 'var(--ochre)' },
|
|
583
|
-
{ label: '未启用', en: 'OFF', value: cacheTotal > 0 ? Math.max(0, 100 - this.cacheHitRate - Math.round((inputTok / cacheTotal) * 100)) : 0, color: 'var(--clay)' },
|
|
584
|
-
];
|
|
585
|
-
const saving = costBreakdown?.cacheSaving || 0;
|
|
586
|
-
this.cacheSavingText = saving > 0 ? `本月缓存命中节省 <span class="font-mono" style="color:var(--forest)">$${saving.toFixed(2)}</span> ≈ 总成本 ${((saving / Math.max(cost, 1)) * 100).toFixed(1)}%` : '';
|
|
587
|
-
|
|
588
|
-
/* Timeline */
|
|
589
|
-
this.renderTimeline(trendData, usageStats);
|
|
590
|
-
|
|
591
|
-
/* Projects */
|
|
592
|
-
const projEntries = Object.entries(usageStats.projects || {}).filter(([, d]) => d.requests > 0).sort((a, b) => b[1].requests - a[1].requests).slice(0, 8);
|
|
593
|
-
this.projectData = projEntries.map(([name, d]) => ({ name: name.length > 20 ? '...' + name.slice(-17) : name, value: d.requests }));
|
|
594
|
-
|
|
595
|
-
/* Tool rank */
|
|
596
|
-
this._computeToolRank();
|
|
597
|
-
|
|
598
|
-
/* Tool rail tokens — only refresh sidebar when viewing all tools */
|
|
599
|
-
if (this.activeTool === 'all') {
|
|
600
|
-
this.computeToolTokens(usageStats, data.toolBreakdown);
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
/* Git insights (existing chart + table) */
|
|
604
|
-
if (gitStats && (gitStats.commits > 0 || gitStats.filesChanged > 0)) {
|
|
605
|
-
renderGitInsights(gitStats, this.activeTool);
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
/* Report view data pre-compute */
|
|
609
|
-
this.computeReportData(data);
|
|
610
|
-
|
|
611
|
-
/* Project list for report view */
|
|
612
|
-
this.reportProjects = Object.keys(data.projectDetails || {}).sort();
|
|
613
|
-
|
|
614
|
-
/* Charts (Chart.js) */
|
|
615
|
-
this.$nextTick(() => this.renderCharts(data));
|
|
616
|
-
},
|
|
617
|
-
|
|
618
|
-
toggleWorkType(idx) {
|
|
619
|
-
const item = this.workTypeData[idx];
|
|
620
|
-
if (!item) return;
|
|
621
|
-
item.hidden = !item.hidden;
|
|
622
|
-
const chart = getChart('workTypeChart');
|
|
623
|
-
if (chart) {
|
|
624
|
-
chart.toggleDataVisibility(idx);
|
|
625
|
-
chart.update();
|
|
626
|
-
}
|
|
627
|
-
},
|
|
628
|
-
|
|
629
|
-
_animatePct(target) {
|
|
630
|
-
if (this._aiPctAnim) cancelAnimationFrame(this._aiPctAnim);
|
|
631
|
-
const start = this.aiLinePctDisplay || 0;
|
|
632
|
-
const duration = 800;
|
|
633
|
-
const t0 = performance.now();
|
|
634
|
-
const tick = (now) => {
|
|
635
|
-
const elapsed = now - t0;
|
|
636
|
-
const progress = Math.min(elapsed / duration, 1);
|
|
637
|
-
const eased = 1 - Math.pow(1 - progress, 3);
|
|
638
|
-
this.aiLinePctDisplay = Math.round(start + (target - start) * eased);
|
|
639
|
-
if (progress < 1) this._aiPctAnim = requestAnimationFrame(tick);
|
|
640
|
-
};
|
|
641
|
-
this._aiPctAnim = requestAnimationFrame(tick);
|
|
642
|
-
},
|
|
643
|
-
|
|
644
|
-
renderAIContribution(gitStats, usageStats) {
|
|
645
|
-
const ai = gitStats?.aiContribution;
|
|
646
|
-
if (!ai || !gitStats || gitStats.commits <= 0) {
|
|
647
|
-
this.aiLinePct = 0;
|
|
648
|
-
this.aiLinePctDisplay = 0;
|
|
649
|
-
if (this._aiPctAnim) cancelAnimationFrame(this._aiPctAnim);
|
|
650
|
-
this.aiSummaryDesc = '暂无 Git 数据';
|
|
651
|
-
return;
|
|
652
|
-
}
|
|
653
|
-
const totalLines = ai.totalLinesChanged || (ai.aiFileLinesAdded + ai.aiFileLinesDeleted + (ai.humanLinesChanged || 0)) || 1;
|
|
654
|
-
const targetPct = Math.round((ai.aiLinesChanged / totalLines) * 100) || Math.round((ai.aiLineRatio || 0) * 100);
|
|
655
|
-
this.aiLinePct = targetPct;
|
|
656
|
-
this._animatePct(targetPct);
|
|
657
|
-
this.aiContributionMeta = `${fmt(ai.aiLinesChanged || 0)} / ${fmt(totalLines)} LINES`;
|
|
658
|
-
|
|
659
|
-
if (gitStats.attributionSummary) {
|
|
660
|
-
const s = gitStats.attributionSummary;
|
|
661
|
-
const upperPct = Math.round(((s.confirmedAILines + s.probableAILines + s.possibleAILines) / (s.totalLinesChanged || 1)) * 100);
|
|
662
|
-
const weightedPct = Math.round((ai.weightedAILineRatio || 0) * 100);
|
|
663
|
-
let desc = '代码变更有 AI 参与';
|
|
664
|
-
if (ai.possibleAICommits > 0) {
|
|
665
|
-
desc += `,可能 AI 影响 <strong>${ai.possibleAICommits}</strong> 提交`;
|
|
666
|
-
}
|
|
667
|
-
if (weightedPct > targetPct) {
|
|
668
|
-
desc += `,加权影响力 <strong>${weightedPct}%</strong>`;
|
|
669
|
-
}
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
this.
|
|
674
|
-
this.
|
|
675
|
-
|
|
676
|
-
this.
|
|
677
|
-
this.
|
|
678
|
-
|
|
679
|
-
this.
|
|
680
|
-
this.
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
{ l: '
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
{ l: '
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
{ l: '
|
|
695
|
-
{ l: 'AI
|
|
696
|
-
{ l: '
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
this.lineBlameEvidence =
|
|
726
|
-
this.lineBlamePrecision =
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
{ l: '
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
const
|
|
746
|
-
const
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
{ l: '
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
const
|
|
782
|
-
const
|
|
783
|
-
const
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
{ l: '
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
}
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
{ l: '
|
|
806
|
-
{ l: '
|
|
807
|
-
{ l: '
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
params.
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
const
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
const
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
continue;
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
if (
|
|
909
|
-
if (line.startsWith('
|
|
910
|
-
if (
|
|
911
|
-
if (line.
|
|
912
|
-
out.push(`<
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
toast
|
|
944
|
-
toast
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
addBtn
|
|
975
|
-
addBtn.
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
const
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
ok
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
inp.
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
tag
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
x
|
|
1012
|
-
tag
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
const
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
const
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
const
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
}
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
const
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
if (hint) { hint.textContent = '
|
|
1144
|
-
|
|
1145
|
-
}
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
const
|
|
1160
|
-
const
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
if (body) body.innerHTML = '<
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1
|
+
import { COLORS, SCENARIO_COLORS, TEXT, ID, STORAGE } from './config.js';
|
|
2
|
+
import { esc, fmt, fmtShort, destroyChart, destroyAllCharts, getChart, setChart, todayISO, fmtDate, TOOL_DISPLAY_NAMES, groupMcpByServer, aggregateToolsWithDualCounts } from './utils.js';
|
|
3
|
+
import { createLatestRequestGuard, fetchTools, fetchReport, fetchConfig, saveConfig, fetchDetails, fetchSessions, fetchStepStats, fetchHooksStatus, updateHooks } from './api.js';
|
|
4
|
+
import { renderWorkTypePie, renderModelBars, renderProjectBars, renderTimelineArea, renderCacheStack } from './charts.js';
|
|
5
|
+
import { renderGitInsights, renderLineBlameEvidence } from './git-insights.js';
|
|
6
|
+
import { loadWorkReport, copyWorkReport, downloadMarkdown, getWorkReportState, setWorkReportState } from './work-report.js';
|
|
7
|
+
import { exportCSV, printReport, exportJSON, exportHTML } from './export.js';
|
|
8
|
+
|
|
9
|
+
/* ── Alpine App Component ── */
|
|
10
|
+
function appState() {
|
|
11
|
+
return {
|
|
12
|
+
/* state */
|
|
13
|
+
view: 'ledger',
|
|
14
|
+
period: 'daily',
|
|
15
|
+
activeTool: 'all',
|
|
16
|
+
railCollapsed: localStorage.getItem(STORAGE.SIDEBAR_COLLAPSED) === 'true',
|
|
17
|
+
theme: localStorage.getItem(STORAGE.THEME) || 'dark',
|
|
18
|
+
currentDate: todayISO(),
|
|
19
|
+
today: todayISO(),
|
|
20
|
+
loading: false,
|
|
21
|
+
error: null,
|
|
22
|
+
hasData: false,
|
|
23
|
+
availableTools: [],
|
|
24
|
+
appName: 'LumenCode',
|
|
25
|
+
appVersion: '',
|
|
26
|
+
lastReportData: null,
|
|
27
|
+
cache: {},
|
|
28
|
+
_cacheOrder: [],
|
|
29
|
+
_cacheMaxSize: 30,
|
|
30
|
+
reportRequestGuard: createLatestRequestGuard(),
|
|
31
|
+
|
|
32
|
+
/* report view state */
|
|
33
|
+
reportLevel: 'detailed',
|
|
34
|
+
reportPlatform: 'default',
|
|
35
|
+
reportProject: '',
|
|
36
|
+
reportProjects: [],
|
|
37
|
+
copied: false,
|
|
38
|
+
reportHtml: '',
|
|
39
|
+
|
|
40
|
+
/* constants */
|
|
41
|
+
customStart: '',
|
|
42
|
+
customEnd: '',
|
|
43
|
+
periods: [
|
|
44
|
+
{ id: 'daily', cn: '日', en: 'DAY' },
|
|
45
|
+
{ id: 'weekly', cn: '周', en: 'WEEK' },
|
|
46
|
+
{ id: 'monthly', cn: '月', en: 'MONTH' },
|
|
47
|
+
{ id: 'custom', cn: '自定义', en: 'CUSTOM' },
|
|
48
|
+
],
|
|
49
|
+
colors: {
|
|
50
|
+
rust: 'var(--rust)', dest: 'var(--dest)', forest: 'var(--forest)',
|
|
51
|
+
ochre: 'var(--ochre)', clay: 'var(--clay)',
|
|
52
|
+
},
|
|
53
|
+
toolColors: { claude: 'var(--claude)', codex: 'var(--codex)', opencode: 'var(--opencode)' },
|
|
54
|
+
toolSubNames: { claude: 'ANTHROPIC', codex: 'OPENAI', opencode: 'OSS' },
|
|
55
|
+
|
|
56
|
+
/* computed getters */
|
|
57
|
+
get periodMeta() { return this.periods.find(p => p.id === this.period) || this.periods[0]; },
|
|
58
|
+
get dateDisplay() {
|
|
59
|
+
if (this.period === 'custom') {
|
|
60
|
+
if (this.customStart && this.customEnd) return `${this.customStart.replace(/-/g, '.')} — ${this.customEnd.replace(/-/g, '.')}`;
|
|
61
|
+
return '选择日期范围';
|
|
62
|
+
}
|
|
63
|
+
if (this.period === 'daily') return this.currentDate.replace(/-/g, '.');
|
|
64
|
+
if (this.period === 'weekly') {
|
|
65
|
+
const d = new Date(this.currentDate);
|
|
66
|
+
const start = new Date(d); start.setDate(d.getDate() - d.getDay() + 1);
|
|
67
|
+
const end = new Date(start); end.setDate(start.getDate() + 6);
|
|
68
|
+
return `${fmtDate(start)} — ${fmtDate(end)}`;
|
|
69
|
+
}
|
|
70
|
+
return this.currentDate.slice(0, 7).replace('-', '.');
|
|
71
|
+
},
|
|
72
|
+
get generatedAt() { return fmtDate(new Date()) + ' · ' + new Date().toLocaleTimeString('zh-CN', {hour:'2-digit',minute:'2-digit'}) + ' UTC+8'; },
|
|
73
|
+
get traceId() { return 'CT-' + this.currentDate.replace(/-/g, '-'); },
|
|
74
|
+
|
|
75
|
+
/* KPI defaults */
|
|
76
|
+
kpiData: [
|
|
77
|
+
{ label: '活跃天数', sub: 'ACTIVE DAYS', value: '-', unit: '/ 31', delta: '', trend: 'flat' },
|
|
78
|
+
{ label: '覆盖项目', sub: 'PROJECTS', value: '-', unit: '个', delta: '', trend: 'flat' },
|
|
79
|
+
{ label: '高峰天数', sub: 'PEAK DAYS', value: '-', unit: '天', delta: '', trend: 'flat' },
|
|
80
|
+
{ label: 'Token 消耗 · 含缓存', sub: 'TOKENS · INC. CACHE', value: '-', unit: 'M', delta: '', trend: 'flat' },
|
|
81
|
+
{ label: '估算成本', sub: 'EST. COST USD', value: '-', unit: '', delta: '', trend: 'flat' },
|
|
82
|
+
],
|
|
83
|
+
|
|
84
|
+
/* AI contribution defaults */
|
|
85
|
+
aiLinePct: 0,
|
|
86
|
+
aiLinePctDisplay: 0,
|
|
87
|
+
_aiPctAnim: null,
|
|
88
|
+
aiSummaryDesc: '',
|
|
89
|
+
attributionPct: '0% / 100%',
|
|
90
|
+
confirmedPct: 0,
|
|
91
|
+
inferredPct: 0,
|
|
92
|
+
unattribPct: 0,
|
|
93
|
+
sourceClaudePct: 0,
|
|
94
|
+
sourceCodexPct: 0,
|
|
95
|
+
sourceOpencodePct: 0,
|
|
96
|
+
sourceBreakdown: [],
|
|
97
|
+
aiContributionMeta: '- / - LINES',
|
|
98
|
+
lineBlameEvidence: null,
|
|
99
|
+
lineBlamePrecision: '',
|
|
100
|
+
stepStats: null,
|
|
101
|
+
stepStatusLabel: '',
|
|
102
|
+
hooksStatus: null,
|
|
103
|
+
hooksBusy: false,
|
|
104
|
+
gitOutputCells: [
|
|
105
|
+
{ l: '提交', en: 'COMMITS', v: '-', c: '' },
|
|
106
|
+
{ l: '变更文件', en: 'FILES', v: '-', c: '' },
|
|
107
|
+
{ l: '新增', en: '+ ADDED', v: '-', c: 'var(--forest)' },
|
|
108
|
+
{ l: '删除', en: '− REMOVED', v: '-', c: 'var(--dest)' },
|
|
109
|
+
],
|
|
110
|
+
attributionCells: [
|
|
111
|
+
{ l: 'AI 改写', en: 'REWRITE', v: '-', c: '' },
|
|
112
|
+
{ l: 'AI 提交', en: 'COMMITS', v: '-', c: 'var(--forest)' },
|
|
113
|
+
{ l: '可能上限', en: 'MAX', v: '-', c: '' },
|
|
114
|
+
{ l: '高·中置信', en: 'HI · MID', v: '-', c: 'var(--ochre)' },
|
|
115
|
+
{ l: 'AI 新增', en: '+ AI', v: '-', c: 'var(--forest)' },
|
|
116
|
+
{ l: 'AI 删除', en: '− AI', v: '-', c: 'var(--dest)' },
|
|
117
|
+
],
|
|
118
|
+
|
|
119
|
+
/* section data defaults */
|
|
120
|
+
editTypeData: [],
|
|
121
|
+
topFilesData: [],
|
|
122
|
+
topFilesMeta: '+0 / −0',
|
|
123
|
+
workTypeData: [],
|
|
124
|
+
modelData: [],
|
|
125
|
+
topModelName: '-',
|
|
126
|
+
activeModels: '-',
|
|
127
|
+
cacheHitRate: 0,
|
|
128
|
+
cacheDelta: '',
|
|
129
|
+
cacheData: [],
|
|
130
|
+
cacheSavingText: '',
|
|
131
|
+
timelineMeta: [
|
|
132
|
+
{ l: 'PEAK DAY', v: '-', s: '-' },
|
|
133
|
+
{ l: 'AVG / DAY', v: '-', s: 'sessions' },
|
|
134
|
+
{ l: 'LONGEST STREAK', v: '-', s: 'consecutive days' },
|
|
135
|
+
{ l: 'IDLE DAYS', v: '-', s: 'no activity' },
|
|
136
|
+
],
|
|
137
|
+
toolRankData: [],
|
|
138
|
+
toolRankTotal: 0,
|
|
139
|
+
toolRankTab: 'all',
|
|
140
|
+
toolRankTotalCalls: 0,
|
|
141
|
+
toolRankAllTotal: 0,
|
|
142
|
+
toolRankSkillTotal: 0,
|
|
143
|
+
toolRankMcpTotal: 0,
|
|
144
|
+
projectData: [],
|
|
145
|
+
|
|
146
|
+
/* tool summary for rail */
|
|
147
|
+
toolTokens: { all: '-' },
|
|
148
|
+
toolSessions: { all: 0 },
|
|
149
|
+
|
|
150
|
+
/* report view data */
|
|
151
|
+
reportKpis: [
|
|
152
|
+
{ l: 'TOKENS', v: '-', s: '估算成本 -', accent: false },
|
|
153
|
+
{ l: 'COMMITS', v: '-', s: '- / - 行', accent: false },
|
|
154
|
+
{ l: 'AI CONTRIBUTION', v: '-', s: '- 行可独立运行', accent: true },
|
|
155
|
+
{ l: 'ACTIVE DAYS', v: '-', s: '连续 - 天最长', accent: false },
|
|
156
|
+
],
|
|
157
|
+
reportSubTitle: '',
|
|
158
|
+
reportSummary: '',
|
|
159
|
+
reportHighlights: [],
|
|
160
|
+
|
|
161
|
+
get hooksNeedAction() {
|
|
162
|
+
if (!this.hooksStatus) return false;
|
|
163
|
+
return !this.hooksStatus.stepsInitialized ||
|
|
164
|
+
!this.hooksStatus.claude?.enabled ||
|
|
165
|
+
!this.hooksStatus.codex?.enabled ||
|
|
166
|
+
!this.hooksStatus.opencode?.enabled;
|
|
167
|
+
},
|
|
168
|
+
|
|
169
|
+
get hooksStatusText() {
|
|
170
|
+
if (!this.hooksStatus) return '正在检查 hooks 状态';
|
|
171
|
+
const total = this.hooksStatus.projectCount ?? this.hooksStatus.claude?.total ?? 0;
|
|
172
|
+
if (this.hooksStatus.targetMode === 'configured-projects') {
|
|
173
|
+
if (total === 0) return '未配置项目,请先在设置中添加项目路径';
|
|
174
|
+
const parts = [
|
|
175
|
+
`Claude ${this.hooksStatus.claude?.enabledCount || 0}/${total}`,
|
|
176
|
+
`Codex ${this.hooksStatus.codex?.enabledCount || 0}/${total}`,
|
|
177
|
+
`OpenCode ${this.hooksStatus.opencode?.enabledCount || 0}/${total}`,
|
|
178
|
+
`steps ${this.hooksStatus.stepsReadyCount || 0}/${total}`,
|
|
179
|
+
];
|
|
180
|
+
return `设置内项目 hooks:${parts.join(' / ')}`;
|
|
181
|
+
}
|
|
182
|
+
const parts = [
|
|
183
|
+
`Claude ${this.hooksStatus.claude?.enabled ? '已开启' : '未开启'}`,
|
|
184
|
+
`Codex ${this.hooksStatus.codex?.enabled ? '已开启' : '未开启'}`,
|
|
185
|
+
`OpenCode ${this.hooksStatus.opencode?.enabled ? '已开启' : '未开启'}`,
|
|
186
|
+
`steps ${this.hooksStatus.stepsInitialized ? '已初始化' : '未初始化'}`,
|
|
187
|
+
];
|
|
188
|
+
return parts.join(' / ');
|
|
189
|
+
},
|
|
190
|
+
|
|
191
|
+
/* ── init ── */
|
|
192
|
+
async init() {
|
|
193
|
+
this.loadStateFromHash();
|
|
194
|
+
if (this.theme === 'dark') document.documentElement.classList.add('dark');
|
|
195
|
+
else document.documentElement.classList.remove('dark');
|
|
196
|
+
this.$watch('view', (value) => {
|
|
197
|
+
if (value === 'ledger' && this.lastReportData) {
|
|
198
|
+
this.$nextTick(() => this.renderCharts(this.lastReportData));
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
await this.loadTools();
|
|
202
|
+
await this.loadHooksStatus();
|
|
203
|
+
await this.loadStepStats();
|
|
204
|
+
// 首次加载时先获取全量数据填充侧边栏,再按当前工具加载
|
|
205
|
+
if (this.activeTool !== 'all') {
|
|
206
|
+
try {
|
|
207
|
+
const allData = await fetchReport({ tool: 'all', period: this.period, date: this.currentDate });
|
|
208
|
+
if (allData && !allData.error) {
|
|
209
|
+
this.computeToolTokens(allData.usageStats, allData.toolBreakdown);
|
|
210
|
+
}
|
|
211
|
+
} catch {}
|
|
212
|
+
}
|
|
213
|
+
await this.loadCurrentView();
|
|
214
|
+
},
|
|
215
|
+
|
|
216
|
+
/* ── theme ── */
|
|
217
|
+
toggleTheme() {
|
|
218
|
+
this.theme = this.theme === 'dark' ? 'light' : 'dark';
|
|
219
|
+
localStorage.setItem(STORAGE.THEME, this.theme);
|
|
220
|
+
if (this.theme === 'dark') document.documentElement.classList.add('dark');
|
|
221
|
+
else document.documentElement.classList.remove('dark');
|
|
222
|
+
/* re-render charts to pick up new colors */
|
|
223
|
+
if (this.lastReportData && this.view === 'ledger') this.renderCharts(this.lastReportData);
|
|
224
|
+
},
|
|
225
|
+
|
|
226
|
+
/* ── tools ── */
|
|
227
|
+
async loadTools() {
|
|
228
|
+
try {
|
|
229
|
+
const data = await fetchTools();
|
|
230
|
+
this.availableTools = data.tools || data || [];
|
|
231
|
+
if (data.appName) this.appName = data.appName;
|
|
232
|
+
if (data.appVersion) this.appVersion = data.appVersion;
|
|
233
|
+
} catch (e) { console.warn('loadTools failed:', e); this.availableTools = []; }
|
|
234
|
+
},
|
|
235
|
+
|
|
236
|
+
async loadStepStats() {
|
|
237
|
+
try {
|
|
238
|
+
const data = await fetchStepStats();
|
|
239
|
+
this.stepStats = data;
|
|
240
|
+
this.stepStatusLabel = data?.available
|
|
241
|
+
? `STEP READY · ${data.stepCount || 0}`
|
|
242
|
+
: 'STEP NOT READY';
|
|
243
|
+
} catch {
|
|
244
|
+
this.stepStats = null;
|
|
245
|
+
this.stepStatusLabel = '';
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
|
|
249
|
+
async loadHooksStatus() {
|
|
250
|
+
try {
|
|
251
|
+
this.hooksStatus = await fetchHooksStatus();
|
|
252
|
+
} catch (e) {
|
|
253
|
+
console.warn('loadHooksStatus failed:', e);
|
|
254
|
+
this.hooksStatus = null;
|
|
255
|
+
}
|
|
256
|
+
},
|
|
257
|
+
|
|
258
|
+
showHooksConfirmModal() {
|
|
259
|
+
const count = this.hooksStatus?.projectCount ?? 0;
|
|
260
|
+
const el = document.getElementById('hooksConfirmCount');
|
|
261
|
+
if (el) el.textContent = count;
|
|
262
|
+
const modal = document.getElementById('hooksConfirmModal');
|
|
263
|
+
if (modal) modal.style.display = 'flex';
|
|
264
|
+
},
|
|
265
|
+
|
|
266
|
+
hideHooksConfirmModal() {
|
|
267
|
+
const modal = document.getElementById('hooksConfirmModal');
|
|
268
|
+
if (modal) modal.style.display = 'none';
|
|
269
|
+
},
|
|
270
|
+
|
|
271
|
+
async enableHooksFromUi() {
|
|
272
|
+
this.hideHooksConfirmModal();
|
|
273
|
+
if (this.hooksBusy) return;
|
|
274
|
+
this.hooksBusy = true;
|
|
275
|
+
try {
|
|
276
|
+
await updateHooks('enable');
|
|
277
|
+
await this.loadHooksStatus();
|
|
278
|
+
await this.loadStepStats();
|
|
279
|
+
showToast('hooks 已开启');
|
|
280
|
+
} catch (err) {
|
|
281
|
+
showToast('开启 hooks 失败: ' + err.message);
|
|
282
|
+
} finally {
|
|
283
|
+
this.hooksBusy = false;
|
|
284
|
+
}
|
|
285
|
+
},
|
|
286
|
+
|
|
287
|
+
showHooksDisableConfirmModal() {
|
|
288
|
+
const modal = document.getElementById('hooksDisableConfirmModal');
|
|
289
|
+
if (modal) modal.style.display = 'flex';
|
|
290
|
+
},
|
|
291
|
+
|
|
292
|
+
hideHooksDisableConfirmModal() {
|
|
293
|
+
const modal = document.getElementById('hooksDisableConfirmModal');
|
|
294
|
+
if (modal) modal.style.display = 'none';
|
|
295
|
+
},
|
|
296
|
+
|
|
297
|
+
async disableHooksFromUi() {
|
|
298
|
+
this.hideHooksDisableConfirmModal();
|
|
299
|
+
if (this.hooksBusy) return;
|
|
300
|
+
this.hooksBusy = true;
|
|
301
|
+
try {
|
|
302
|
+
await updateHooks('disable');
|
|
303
|
+
await this.loadHooksStatus();
|
|
304
|
+
await this.loadStepStats();
|
|
305
|
+
showToast('hooks 已关闭');
|
|
306
|
+
} catch (err) {
|
|
307
|
+
showToast('关闭 hooks 失败: ' + err.message);
|
|
308
|
+
} finally {
|
|
309
|
+
this.hooksBusy = false;
|
|
310
|
+
}
|
|
311
|
+
},
|
|
312
|
+
|
|
313
|
+
setTool(name) {
|
|
314
|
+
this.activeTool = name;
|
|
315
|
+
this.loadCurrentView();
|
|
316
|
+
if (this.view === 'report') this.loadReportContent();
|
|
317
|
+
},
|
|
318
|
+
|
|
319
|
+
setToolRankTab(tab) {
|
|
320
|
+
this.toolRankTab = tab;
|
|
321
|
+
this._computeToolRank();
|
|
322
|
+
const container = document.getElementById('toolCallsContainer');
|
|
323
|
+
if (container) container.scrollTop = 0;
|
|
324
|
+
},
|
|
325
|
+
|
|
326
|
+
_computeToolRank() {
|
|
327
|
+
const usageStats = this._lastUsageStats || {};
|
|
328
|
+
const tab = this.toolRankTab;
|
|
329
|
+
const getCalls = (val) => typeof val === 'number' ? val : (val.calls || 0);
|
|
330
|
+
const getUses = (val) => typeof val === 'number' ? val : (val.uses || 0);
|
|
331
|
+
const sumCalls = (obj) => Object.values(obj || {}).reduce((s, v) => s + getCalls(v), 0);
|
|
332
|
+
|
|
333
|
+
this.toolRankAllTotal = sumCalls(usageStats.tools);
|
|
334
|
+
this.toolRankSkillTotal = sumCalls(usageStats.skills);
|
|
335
|
+
this.toolRankMcpTotal = sumCalls(usageStats.mcpTools);
|
|
336
|
+
|
|
337
|
+
if (tab === 'all') {
|
|
338
|
+
const dual = aggregateToolsWithDualCounts(usageStats.tools || {});
|
|
339
|
+
const entries = Object.entries(dual).sort((a, b) => b[1].uses - a[1].uses);
|
|
340
|
+
const maxUses = Math.max(...entries.map(([, v]) => v.uses), 1);
|
|
341
|
+
this.toolRankData = entries.map(([name, d]) => ({
|
|
342
|
+
name,
|
|
343
|
+
calls: d.calls,
|
|
344
|
+
uses: d.uses,
|
|
345
|
+
value: d.calls,
|
|
346
|
+
pct: Math.round((d.uses / maxUses) * 100),
|
|
347
|
+
displayName: TOOL_DISPLAY_NAMES[name] || '',
|
|
348
|
+
}));
|
|
349
|
+
this.toolRankTotalCalls = this.toolRankAllTotal;
|
|
350
|
+
} else if (tab === 'skill') {
|
|
351
|
+
const skills = usageStats.skills || {};
|
|
352
|
+
const entries = Object.entries(skills).sort((a, b) => getUses(b[1]) - getUses(a[1]));
|
|
353
|
+
const maxUses = Math.max(...entries.map(([, v]) => getUses(v)), 1);
|
|
354
|
+
this.toolRankData = entries.map(([name, val]) => {
|
|
355
|
+
const calls = getCalls(val);
|
|
356
|
+
const uses = getUses(val);
|
|
357
|
+
return {
|
|
358
|
+
name,
|
|
359
|
+
calls,
|
|
360
|
+
uses,
|
|
361
|
+
value: calls,
|
|
362
|
+
pct: Math.round((uses / maxUses) * 100),
|
|
363
|
+
displayName: '',
|
|
364
|
+
};
|
|
365
|
+
});
|
|
366
|
+
this.toolRankTotalCalls = this.toolRankSkillTotal;
|
|
367
|
+
} else if (tab === 'mcp') {
|
|
368
|
+
this.toolRankData = groupMcpByServer(usageStats.mcpTools || {});
|
|
369
|
+
this.toolRankTotalCalls = this.toolRankMcpTotal;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
this.toolRankTotal = this.toolRankData.length;
|
|
373
|
+
let rank = 0;
|
|
374
|
+
for (const item of this.toolRankData) {
|
|
375
|
+
if (!item.isGroup) item.rank = ++rank;
|
|
376
|
+
}
|
|
377
|
+
},
|
|
378
|
+
|
|
379
|
+
/* ── period / date ── */
|
|
380
|
+
setPeriod(p) {
|
|
381
|
+
this.period = p;
|
|
382
|
+
if (p !== 'custom') {
|
|
383
|
+
this.customStart = '';
|
|
384
|
+
this.customEnd = '';
|
|
385
|
+
this.saveStateToHash();
|
|
386
|
+
this.loadCurrentView();
|
|
387
|
+
if (this.view === 'report') this.loadReportContent();
|
|
388
|
+
}
|
|
389
|
+
},
|
|
390
|
+
|
|
391
|
+
onCustomStartChange() {
|
|
392
|
+
if (this.customStart && this.customEnd) {
|
|
393
|
+
this.loadCurrentView();
|
|
394
|
+
if (this.view === 'report') this.loadReportContent();
|
|
395
|
+
}
|
|
396
|
+
},
|
|
397
|
+
|
|
398
|
+
onCustomEndChange() {
|
|
399
|
+
if (this.customStart && this.customEnd) {
|
|
400
|
+
this.loadCurrentView();
|
|
401
|
+
if (this.view === 'report') this.loadReportContent();
|
|
402
|
+
}
|
|
403
|
+
},
|
|
404
|
+
|
|
405
|
+
shiftDate(dir) {
|
|
406
|
+
const d = new Date(this.currentDate);
|
|
407
|
+
if (this.period === 'monthly') {
|
|
408
|
+
d.setMonth(d.getMonth() + dir);
|
|
409
|
+
} else {
|
|
410
|
+
const step = this.period === 'weekly' ? 7 * dir : dir;
|
|
411
|
+
d.setDate(d.getDate() + step);
|
|
412
|
+
}
|
|
413
|
+
this.currentDate = d.toISOString().slice(0, 10);
|
|
414
|
+
this.saveStateToHash();
|
|
415
|
+
this.loadCurrentView();
|
|
416
|
+
if (this.view === 'report') this.loadReportContent();
|
|
417
|
+
},
|
|
418
|
+
|
|
419
|
+
onDateChange() {
|
|
420
|
+
if (this.currentDate > this.today) this.currentDate = this.today;
|
|
421
|
+
this.saveStateToHash();
|
|
422
|
+
this.loadCurrentView();
|
|
423
|
+
if (this.view === 'report') this.loadReportContent();
|
|
424
|
+
},
|
|
425
|
+
|
|
426
|
+
loadStateFromHash() {
|
|
427
|
+
const hash = location.hash.slice(1);
|
|
428
|
+
if (!hash) return;
|
|
429
|
+
const [p, d] = hash.split('/');
|
|
430
|
+
if (p && ['daily', 'weekly', 'monthly', 'custom'].includes(p)) this.period = p;
|
|
431
|
+
if (d && /^\d{4}-\d{2}-\d{2}$/.test(d)) this.currentDate = d;
|
|
432
|
+
},
|
|
433
|
+
|
|
434
|
+
saveStateToHash() {
|
|
435
|
+
location.hash = `${this.period}/${this.currentDate}`;
|
|
436
|
+
},
|
|
437
|
+
|
|
438
|
+
/* ── data loading ── */
|
|
439
|
+
async loadCurrentView() {
|
|
440
|
+
const cacheKey = `${this.activeTool}-${this.period}-${this.period === 'custom' ? this.customStart + '~' + this.customEnd : this.currentDate}`;
|
|
441
|
+
const request = this.reportRequestGuard.next();
|
|
442
|
+
|
|
443
|
+
if (this.cache[cacheKey]) {
|
|
444
|
+
const idx = this._cacheOrder.indexOf(cacheKey);
|
|
445
|
+
if (idx !== -1) { this._cacheOrder.splice(idx, 1); this._cacheOrder.push(cacheKey); }
|
|
446
|
+
this.renderData(this.cache[cacheKey]);
|
|
447
|
+
this.loading = false;
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
this.loading = true;
|
|
452
|
+
this.error = null;
|
|
453
|
+
|
|
454
|
+
try {
|
|
455
|
+
const params = { tool: this.activeTool, period: this.period, date: this.currentDate };
|
|
456
|
+
if (this.period === 'custom' && this.customStart && this.customEnd) {
|
|
457
|
+
params.start = this.customStart;
|
|
458
|
+
params.end = this.customEnd;
|
|
459
|
+
}
|
|
460
|
+
const data = await fetchReport(params, request.signal);
|
|
461
|
+
if (!request.isCurrent()) return;
|
|
462
|
+
|
|
463
|
+
if (!data || data.error) {
|
|
464
|
+
this.hasData = false;
|
|
465
|
+
if (data?.error === TEXT.NOT_CONFIGURED) {
|
|
466
|
+
this.showWelcome();
|
|
467
|
+
}
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
this.hideWelcome();
|
|
472
|
+
this.cache[cacheKey] = data;
|
|
473
|
+
this._cacheOrder.push(cacheKey);
|
|
474
|
+
while (this._cacheOrder.length > this._cacheMaxSize) {
|
|
475
|
+
const old = this._cacheOrder.shift();
|
|
476
|
+
delete this.cache[old];
|
|
477
|
+
}
|
|
478
|
+
this.lastReportData = data;
|
|
479
|
+
this.renderData(data);
|
|
480
|
+
} catch (err) {
|
|
481
|
+
if (err.name === 'AbortError') return;
|
|
482
|
+
this.error = err.message;
|
|
483
|
+
showToast('加载失败: ' + err.message);
|
|
484
|
+
} finally {
|
|
485
|
+
if (request.isCurrent()) this.loading = false;
|
|
486
|
+
}
|
|
487
|
+
},
|
|
488
|
+
|
|
489
|
+
showWelcome() {
|
|
490
|
+
const wp = document.getElementById(ID.WELCOME_PAGE);
|
|
491
|
+
if (wp) wp.style.display = 'flex';
|
|
492
|
+
},
|
|
493
|
+
|
|
494
|
+
hideWelcome() {
|
|
495
|
+
const wp = document.getElementById(ID.WELCOME_PAGE);
|
|
496
|
+
if (wp) wp.style.display = 'none';
|
|
497
|
+
},
|
|
498
|
+
|
|
499
|
+
/* ── render data ── */
|
|
500
|
+
renderData(data) {
|
|
501
|
+
const { usageStats, gitStats, start, end, prevStats, trendData, costBreakdown } = data;
|
|
502
|
+
this._lastUsageStats = usageStats;
|
|
503
|
+
this.hasData = usageStats.requestCount > 0;
|
|
504
|
+
if (!this.hasData) {
|
|
505
|
+
this.kpiData = [
|
|
506
|
+
{ label: '活跃天数', sub: 'ACTIVE DAYS', value: '-', unit: '/ ' + (this.period === 'daily' ? '1' : this.period === 'weekly' ? '7' : '31'), delta: '', trend: 'flat' },
|
|
507
|
+
{ label: '覆盖项目', sub: 'PROJECTS', value: '0', unit: '个', delta: '', trend: 'flat' },
|
|
508
|
+
{ label: '高峰天数', sub: 'PEAK DAYS', value: '-', unit: '天', delta: '', trend: 'flat' },
|
|
509
|
+
{ label: 'Token 消耗 · 含缓存', sub: 'TOKENS · INC. CACHE', value: '0.00', unit: 'M', delta: '', trend: 'flat' },
|
|
510
|
+
{ label: '估算成本', sub: 'EST. COST USD', value: '$0.00', unit: '', delta: '', trend: 'flat' },
|
|
511
|
+
];
|
|
512
|
+
destroyAllCharts(['workTypeChart', 'modelChart', 'projectChart', 'toolChart', 'timelineChart', 'commitTypeChart', 'cacheChart']);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/* KPI strip */
|
|
517
|
+
const days = Object.keys(usageStats.dailyStats || {}).length || 1;
|
|
518
|
+
const totalMin = Math.round((usageStats.requestCount || 0) * 2.4);
|
|
519
|
+
const peakDay = Object.entries(usageStats.dailyStats || {}).sort((a, b) => (b[1].requests || 0) - (a[1].requests || 0))[0];
|
|
520
|
+
const tokensM = (usageStats.totalTokens / 1_000_000).toFixed(2);
|
|
521
|
+
const cost = usageStats.estimatedCost || 0;
|
|
522
|
+
const prevCost = prevStats?.estimatedCost || 0;
|
|
523
|
+
const costDelta = prevCost > 0 ? ((cost - prevCost) / prevCost * 100).toFixed(1) : 0;
|
|
524
|
+
const costTrend = cost > prevCost ? 'up' : cost < prevCost ? 'down' : 'flat';
|
|
525
|
+
|
|
526
|
+
this.kpiData = [
|
|
527
|
+
{ label: '活跃天数', sub: 'ACTIVE DAYS', value: String(days), unit: '/ ' + (this.period === 'daily' ? '1' : this.period === 'weekly' ? '7' : '31'), delta: '', trend: 'flat' },
|
|
528
|
+
{ label: '覆盖项目', sub: 'PROJECTS', value: String(Object.keys(usageStats.projects || {}).length), unit: '个', delta: '', trend: 'flat' },
|
|
529
|
+
{ label: '高峰天数', sub: 'PEAK DAYS', value: peakDay ? peakDay[0].slice(5) : '-', unit: '天', delta: '', trend: 'flat' },
|
|
530
|
+
{ label: 'Token 消耗 · 含缓存', sub: 'TOKENS · INC. CACHE', value: tokensM, unit: 'M', delta: '', trend: 'flat' },
|
|
531
|
+
{ label: '估算成本', sub: 'EST. COST USD', value: '$' + cost.toFixed(2), unit: '', delta: (costDelta > 0 ? '+' : '') + costDelta + '%', trend: costTrend },
|
|
532
|
+
];
|
|
533
|
+
|
|
534
|
+
/* AI contribution */
|
|
535
|
+
this.renderAIContribution(gitStats, usageStats);
|
|
536
|
+
|
|
537
|
+
/* Edit types (commit types) */
|
|
538
|
+
const typeEntries = gitStats?.commitTypes ? Object.entries(gitStats.commitTypes).filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]) : [];
|
|
539
|
+
const maxType = Math.max(...typeEntries.map(([, v]) => v), 1);
|
|
540
|
+
const inkSteps = ['var(--rust)', 'var(--ink-82)', 'var(--ink-62)', 'var(--ink-46)', 'var(--ink-32)', 'var(--ink-22)'];
|
|
541
|
+
this.editTypeData = typeEntries.map(([name, value], idx) => ({
|
|
542
|
+
name, value, pct: Math.round((value / maxType) * 100),
|
|
543
|
+
color: inkSteps[Math.min(idx, inkSteps.length - 1)],
|
|
544
|
+
}));
|
|
545
|
+
|
|
546
|
+
/* Top files */
|
|
547
|
+
const hotspots = gitStats?.fileHotspots || [];
|
|
548
|
+
this.topFilesData = hotspots.slice(0, 10).map(h => ({ path: h.path, commits: h.touches, plus: h.added, minus: h.deleted }));
|
|
549
|
+
const totalAdded = hotspots.reduce((s, h) => s + (h.added || 0), 0);
|
|
550
|
+
const totalDeleted = hotspots.reduce((s, h) => s + (h.deleted || 0), 0);
|
|
551
|
+
this.topFilesMeta = `+${fmt(totalAdded)} / −${fmt(totalDeleted)}`;
|
|
552
|
+
|
|
553
|
+
/* Work type (scenarios) */
|
|
554
|
+
const scenarioEntries = Object.entries(usageStats.scenarios || {}).filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]);
|
|
555
|
+
const totalScenario = scenarioEntries.reduce((s, [, v]) => s + v, 0) || 1;
|
|
556
|
+
this.workTypeData = scenarioEntries.map(([name, value], i) => ({
|
|
557
|
+
name, value: Math.round((value / totalScenario) * 100),
|
|
558
|
+
color: SCENARIO_COLORS[name] || '#888',
|
|
559
|
+
hidden: false,
|
|
560
|
+
}));
|
|
561
|
+
|
|
562
|
+
/* Models */
|
|
563
|
+
const modelEntries = Object.entries(usageStats.models || {}).sort((a, b) => b[1].count - a[1].count);
|
|
564
|
+
const maxModel = Math.max(...modelEntries.map(([, v]) => v.count), 1);
|
|
565
|
+
const totalModelReq = modelEntries.reduce((s, [, v]) => s + v.count, 0) || 1;
|
|
566
|
+
this.modelData = modelEntries.map(([name, d]) => ({
|
|
567
|
+
name, pct: Math.round((d.count / totalModelReq) * 100),
|
|
568
|
+
barPct: Math.round((d.count / maxModel) * 100),
|
|
569
|
+
}));
|
|
570
|
+
this.topModelName = modelEntries[0]?.[0] || '-';
|
|
571
|
+
this.activeModels = `${modelEntries.length} / 12`;
|
|
572
|
+
|
|
573
|
+
/* Cache */
|
|
574
|
+
const cacheRead = usageStats.cacheRead || 0;
|
|
575
|
+
const cacheCreate = usageStats.cacheCreate || 0;
|
|
576
|
+
const inputTok = usageStats.inputTokens || 1;
|
|
577
|
+
const cacheTotal = cacheRead + cacheCreate + inputTok;
|
|
578
|
+
this.cacheHitRate = cacheTotal > 0 ? Math.round((cacheRead / cacheTotal) * 100) : 0;
|
|
579
|
+
this.cacheDelta = cacheRead > 0 ? '+17pp' : '';
|
|
580
|
+
this.cacheData = [
|
|
581
|
+
{ label: '命中', en: 'HIT', value: this.cacheHitRate, color: 'var(--forest)' },
|
|
582
|
+
{ label: '未命中', en: 'MISS', value: cacheTotal > 0 ? Math.round((inputTok / cacheTotal) * 100) : 0, color: 'var(--ochre)' },
|
|
583
|
+
{ label: '未启用', en: 'OFF', value: cacheTotal > 0 ? Math.max(0, 100 - this.cacheHitRate - Math.round((inputTok / cacheTotal) * 100)) : 0, color: 'var(--clay)' },
|
|
584
|
+
];
|
|
585
|
+
const saving = costBreakdown?.cacheSaving || 0;
|
|
586
|
+
this.cacheSavingText = saving > 0 ? `本月缓存命中节省 <span class="font-mono" style="color:var(--forest)">$${saving.toFixed(2)}</span> ≈ 总成本 ${((saving / Math.max(cost, 1)) * 100).toFixed(1)}%` : '';
|
|
587
|
+
|
|
588
|
+
/* Timeline */
|
|
589
|
+
this.renderTimeline(trendData, usageStats);
|
|
590
|
+
|
|
591
|
+
/* Projects */
|
|
592
|
+
const projEntries = Object.entries(usageStats.projects || {}).filter(([, d]) => d.requests > 0).sort((a, b) => b[1].requests - a[1].requests).slice(0, 8);
|
|
593
|
+
this.projectData = projEntries.map(([name, d]) => ({ name: name.length > 20 ? '...' + name.slice(-17) : name, value: d.requests }));
|
|
594
|
+
|
|
595
|
+
/* Tool rank */
|
|
596
|
+
this._computeToolRank();
|
|
597
|
+
|
|
598
|
+
/* Tool rail tokens — only refresh sidebar when viewing all tools */
|
|
599
|
+
if (this.activeTool === 'all') {
|
|
600
|
+
this.computeToolTokens(usageStats, data.toolBreakdown);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/* Git insights (existing chart + table) */
|
|
604
|
+
if (gitStats && (gitStats.commits > 0 || gitStats.filesChanged > 0)) {
|
|
605
|
+
renderGitInsights(gitStats, this.activeTool);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/* Report view data pre-compute */
|
|
609
|
+
this.computeReportData(data);
|
|
610
|
+
|
|
611
|
+
/* Project list for report view */
|
|
612
|
+
this.reportProjects = Object.keys(data.projectDetails || {}).sort();
|
|
613
|
+
|
|
614
|
+
/* Charts (Chart.js) */
|
|
615
|
+
this.$nextTick(() => this.renderCharts(data));
|
|
616
|
+
},
|
|
617
|
+
|
|
618
|
+
toggleWorkType(idx) {
|
|
619
|
+
const item = this.workTypeData[idx];
|
|
620
|
+
if (!item) return;
|
|
621
|
+
item.hidden = !item.hidden;
|
|
622
|
+
const chart = getChart('workTypeChart');
|
|
623
|
+
if (chart) {
|
|
624
|
+
chart.toggleDataVisibility(idx);
|
|
625
|
+
chart.update();
|
|
626
|
+
}
|
|
627
|
+
},
|
|
628
|
+
|
|
629
|
+
_animatePct(target) {
|
|
630
|
+
if (this._aiPctAnim) cancelAnimationFrame(this._aiPctAnim);
|
|
631
|
+
const start = this.aiLinePctDisplay || 0;
|
|
632
|
+
const duration = 800;
|
|
633
|
+
const t0 = performance.now();
|
|
634
|
+
const tick = (now) => {
|
|
635
|
+
const elapsed = now - t0;
|
|
636
|
+
const progress = Math.min(elapsed / duration, 1);
|
|
637
|
+
const eased = 1 - Math.pow(1 - progress, 3);
|
|
638
|
+
this.aiLinePctDisplay = Math.round(start + (target - start) * eased);
|
|
639
|
+
if (progress < 1) this._aiPctAnim = requestAnimationFrame(tick);
|
|
640
|
+
};
|
|
641
|
+
this._aiPctAnim = requestAnimationFrame(tick);
|
|
642
|
+
},
|
|
643
|
+
|
|
644
|
+
renderAIContribution(gitStats, usageStats) {
|
|
645
|
+
const ai = gitStats?.aiContribution;
|
|
646
|
+
if (!ai || !gitStats || gitStats.commits <= 0) {
|
|
647
|
+
this.aiLinePct = 0;
|
|
648
|
+
this.aiLinePctDisplay = 0;
|
|
649
|
+
if (this._aiPctAnim) cancelAnimationFrame(this._aiPctAnim);
|
|
650
|
+
this.aiSummaryDesc = '暂无 Git 数据';
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
const totalLines = ai.totalLinesChanged || (ai.aiFileLinesAdded + ai.aiFileLinesDeleted + (ai.humanLinesChanged || 0)) || 1;
|
|
654
|
+
const targetPct = Math.round((ai.aiLinesChanged / totalLines) * 100) || Math.round((ai.aiLineRatio || 0) * 100);
|
|
655
|
+
this.aiLinePct = targetPct;
|
|
656
|
+
this._animatePct(targetPct);
|
|
657
|
+
this.aiContributionMeta = `${fmt(ai.aiLinesChanged || 0)} / ${fmt(totalLines)} LINES`;
|
|
658
|
+
|
|
659
|
+
if (gitStats.attributionSummary) {
|
|
660
|
+
const s = gitStats.attributionSummary;
|
|
661
|
+
const upperPct = Math.round(((s.confirmedAILines + s.probableAILines + s.possibleAILines) / (s.totalLinesChanged || 1)) * 100);
|
|
662
|
+
const weightedPct = Math.round((ai.weightedAILineRatio || 0) * 100);
|
|
663
|
+
let desc = '代码变更有 AI 参与';
|
|
664
|
+
if (ai.possibleAICommits > 0) {
|
|
665
|
+
desc += `,可能 AI 影响 <strong>${ai.possibleAICommits}</strong> 提交`;
|
|
666
|
+
}
|
|
667
|
+
if (weightedPct > targetPct) {
|
|
668
|
+
desc += `,加权影响力 <strong>${weightedPct}%</strong>`;
|
|
669
|
+
}
|
|
670
|
+
if (s.mergeCommits > 0) {
|
|
671
|
+
desc += `,已排除 <strong>${s.mergeCommits}</strong> 个合并提交`;
|
|
672
|
+
}
|
|
673
|
+
this.aiSummaryDesc = desc;
|
|
674
|
+
this.confirmedPct = Math.round((s.confirmedAILines / (s.totalLinesChanged || 1)) * 100);
|
|
675
|
+
this.inferredPct = Math.round((s.probableAILines / (s.totalLinesChanged || 1)) * 100);
|
|
676
|
+
this.unattribPct = Math.max(0, 100 - this.confirmedPct - this.inferredPct);
|
|
677
|
+
this.attributionPct = `${this.confirmedPct}% / ${upperPct}%`;
|
|
678
|
+
} else {
|
|
679
|
+
this.aiSummaryDesc = '代码变更有 AI 参与';
|
|
680
|
+
this.confirmedPct = this.aiLinePct;
|
|
681
|
+
this.inferredPct = 0;
|
|
682
|
+
this.unattribPct = 100 - this.aiLinePct;
|
|
683
|
+
this.attributionPct = `${this.aiLinePct}% / 100%`;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const commitPct = Math.round((ai.aiCommits / gitStats.commits) * 100);
|
|
687
|
+
this.gitOutputCells = [
|
|
688
|
+
{ l: '提交', en: 'COMMITS', v: String(gitStats.commits), c: '' },
|
|
689
|
+
{ l: '变更文件', en: 'FILES', v: String(gitStats.filesChanged), c: '' },
|
|
690
|
+
{ l: '新增', en: '+ ADDED', v: '+' + fmt(gitStats.linesAdded), c: 'var(--forest)' },
|
|
691
|
+
{ l: '删除', en: '− REMOVED', v: '−' + fmt(gitStats.linesDeleted), c: 'var(--dest)' },
|
|
692
|
+
];
|
|
693
|
+
this.attributionCells = [
|
|
694
|
+
{ l: 'AI 改写', en: 'REWRITE', v: this.aiLinePct + '%', c: '' },
|
|
695
|
+
{ l: 'AI 提交', en: 'COMMITS', v: `${ai.aiCommits}/${gitStats.commits}`, c: 'var(--forest)' },
|
|
696
|
+
{ l: '可能上限', en: 'MAX', v: (this.confirmedPct + this.inferredPct) + '%', c: '' },
|
|
697
|
+
{ l: '高·中置信', en: 'HI · MID', v: `${ai.highConfidenceCommits}/${ai.mediumConfidenceCommits}`, c: 'var(--ochre)' },
|
|
698
|
+
{ l: 'AI 新增', en: '+ AI', v: '+' + fmt(ai.aiFileLinesAdded), c: 'var(--forest)' },
|
|
699
|
+
{ l: 'AI 删除', en: '− AI', v: '−' + fmt(ai.aiFileLinesDeleted), c: 'var(--dest)' },
|
|
700
|
+
];
|
|
701
|
+
|
|
702
|
+
/* Source breakdown from real toolBreakdown data */
|
|
703
|
+
const toolTokMap = {};
|
|
704
|
+
const toolColors = { claude: 'var(--claude)', codex: 'var(--codex)', opencode: 'var(--opencode)' };
|
|
705
|
+
const toolDisplayNames = { claude: 'Claude Code', codex: 'OpenAI Codex', opencode: 'OpenCode' };
|
|
706
|
+
if (usageStats.toolBreakdown) {
|
|
707
|
+
for (const [k, v] of Object.entries(usageStats.toolBreakdown)) {
|
|
708
|
+
toolTokMap[k] = (v.inputTokens || 0) + (v.outputTokens || 0);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
const entries = Object.entries(toolTokMap).filter(([, v]) => v > 0);
|
|
712
|
+
const totalToolTok = entries.reduce((s, [, v]) => s + v, 0) || 1;
|
|
713
|
+
const sorted = entries.sort((a, b) => b[1] - a[1]);
|
|
714
|
+
let pctSum = 0;
|
|
715
|
+
this.sourceBreakdown = sorted.map(([name, tok], i) => {
|
|
716
|
+
const isLast = i === sorted.length - 1;
|
|
717
|
+
const pct = isLast ? Math.max(0, 100 - pctSum) : Math.round((tok / totalToolTok) * 100);
|
|
718
|
+
pctSum += pct;
|
|
719
|
+
return { name: toolDisplayNames[name] || name, pct, tokens: fmtShort(tok), color: toolColors[name] || 'var(--foreground)' };
|
|
720
|
+
});
|
|
721
|
+
|
|
722
|
+
/* Line-level blame evidence */
|
|
723
|
+
const blameEv = renderLineBlameEvidence(gitStats?.commitList);
|
|
724
|
+
if (blameEv) {
|
|
725
|
+
this.lineBlameEvidence = blameEv;
|
|
726
|
+
this.lineBlamePrecision = `行级归因: ${blameEv.aiLines}/${blameEv.totalLines} 行 (${blameEv.precision}%) · ${blameEv.commitCount} 提交`;
|
|
727
|
+
} else {
|
|
728
|
+
this.lineBlameEvidence = null;
|
|
729
|
+
this.lineBlamePrecision = '';
|
|
730
|
+
}
|
|
731
|
+
},
|
|
732
|
+
|
|
733
|
+
renderTimeline(trendData, usageStats) {
|
|
734
|
+
const dailyStats = trendData?.dailyStats || {};
|
|
735
|
+
const dates = Object.keys(dailyStats).sort();
|
|
736
|
+
if (dates.length === 0) {
|
|
737
|
+
this.timelineMeta = [
|
|
738
|
+
{ l: 'PEAK DAY', v: '-', s: '-' },
|
|
739
|
+
{ l: 'AVG / DAY', v: '-', s: 'sessions' },
|
|
740
|
+
{ l: 'LONGEST STREAK', v: '-', s: 'consecutive days' },
|
|
741
|
+
{ l: 'IDLE DAYS', v: '-', s: 'no activity' },
|
|
742
|
+
];
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
const sessionsArr = dates.map(d => dailyStats[d].requests || 0);
|
|
746
|
+
const tokensArr = dates.map(d => ((dailyStats[d].inputTokens || 0) + (dailyStats[d].outputTokens || 0)) / 1_000_000);
|
|
747
|
+
const maxSess = Math.max(...sessionsArr);
|
|
748
|
+
const maxIdx = sessionsArr.indexOf(maxSess);
|
|
749
|
+
const avgSess = (sessionsArr.reduce((s, v) => s + v, 0) / sessionsArr.length).toFixed(1);
|
|
750
|
+
this.timelineMeta = [
|
|
751
|
+
{ l: 'PEAK DAY', v: dates[maxIdx]?.slice(5).replace('-', '.') || '-', s: maxSess + ' sessions' },
|
|
752
|
+
{ l: 'AVG / DAY', v: avgSess, s: 'sessions' },
|
|
753
|
+
{ l: 'LONGEST STREAK', v: '-', s: 'consecutive days' },
|
|
754
|
+
{ l: 'IDLE DAYS', v: '-', s: 'no activity' },
|
|
755
|
+
];
|
|
756
|
+
},
|
|
757
|
+
|
|
758
|
+
computeToolTokens(usageStats, toolBreakdown) {
|
|
759
|
+
if (!toolBreakdown || Object.keys(toolBreakdown).length === 0) {
|
|
760
|
+
const total = usageStats.totalTokens || 0;
|
|
761
|
+
this.toolTokens = { all: total >= 1_000_000 ? (total / 1_000_000).toFixed(2) + 'M' : fmtShort(total) };
|
|
762
|
+
this.toolSessions = { all: usageStats.sessionCount || 0 };
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
// 从 toolBreakdown 聚合计算 all 值,确保与各工具之和一致
|
|
766
|
+
let allTok = 0;
|
|
767
|
+
let allSess = 0;
|
|
768
|
+
for (const [name, data] of Object.entries(toolBreakdown)) {
|
|
769
|
+
const tok = (data.inputTokens || 0) + (data.outputTokens || 0) + (data.cacheRead || 0) + (data.cacheCreate || 0);
|
|
770
|
+
allTok += tok;
|
|
771
|
+
const sess = data.sessionCount || data.sessions || 0;
|
|
772
|
+
allSess += sess;
|
|
773
|
+
this.toolTokens[name] = tok >= 1_000_000 ? (tok / 1_000_000).toFixed(2) + 'M' : fmtShort(tok);
|
|
774
|
+
this.toolSessions[name] = sess;
|
|
775
|
+
}
|
|
776
|
+
this.toolTokens.all = allTok >= 1_000_000 ? (allTok / 1_000_000).toFixed(2) + 'M' : fmtShort(allTok);
|
|
777
|
+
this.toolSessions.all = allSess;
|
|
778
|
+
},
|
|
779
|
+
|
|
780
|
+
computeReportData(data) {
|
|
781
|
+
const { usageStats, gitStats, start, end, prevStats } = data;
|
|
782
|
+
const cost = usageStats.estimatedCost || 0;
|
|
783
|
+
const ai = gitStats?.aiContribution;
|
|
784
|
+
const aiPct = ai ? Math.round((ai.aiLinesChanged / (ai.totalLinesChanged || 1)) * 100) : 0;
|
|
785
|
+
const weightedPct = ai ? Math.round((ai.weightedAILineRatio || 0) * 100) : 0;
|
|
786
|
+
const days = Object.keys(usageStats.dailyStats || {}).length || 1;
|
|
787
|
+
let aiSubText = `${fmt(ai?.aiLinesChanged || 0)} 行严格可认定`;
|
|
788
|
+
if (ai?.possibleAICommits > 0) {
|
|
789
|
+
aiSubText += `,${ai.possibleAICommits} 提交可能 AI 参与`;
|
|
790
|
+
}
|
|
791
|
+
this.reportKpis = [
|
|
792
|
+
{ l: 'TOKENS', v: (usageStats.totalTokens / 1_000_000).toFixed(2) + 'M', s: `估算成本 $${cost.toFixed(2)}`, accent: false },
|
|
793
|
+
{ l: 'COMMITS', v: String(gitStats?.commits || 0), s: `+${fmt(gitStats?.linesAdded || 0)} / −${fmt(gitStats?.linesDeleted || 0)} 行`, accent: false },
|
|
794
|
+
{ l: 'AI CONTRIBUTION', v: aiPct + '%', s: aiSubText, accent: true },
|
|
795
|
+
{ l: 'ACTIVE DAYS', v: days + ' / ' + (this.period === 'weekly' ? '7' : '31'), s: '连续 - 天最长', accent: false },
|
|
796
|
+
];
|
|
797
|
+
this.reportSubTitle = `生成 ${start}${end !== start ? ' ~ ' + end : ''} · 来源 ${this.availableTools.length + 1} 个工具`;
|
|
798
|
+
let summaryText = `本${this.periodMeta.cn}跨 ${this.availableTools.length + 1} 个 AI 编程工具汇总 <span class="font-mono" style="background:var(--ink-12);padding:2px 6px;border-radius:4px;">${days}</span> 个活跃工作日,消耗 <span class="font-mono" style="background:var(--ink-12);padding:2px 6px;border-radius:4px;">${(usageStats.totalTokens / 1_000_000).toFixed(2)}M</span> tokens,估算成本 <span class="font-mono" style="background:var(--ink-12);padding:2px 6px;border-radius:4px;">$${cost.toFixed(2)}</span>。AI 贡献率 <span class="font-mono" style="background:var(--ink-12);padding:2px 6px;border-radius:4px;color:var(--rust)">${aiPct}%</span>`;
|
|
799
|
+
if (weightedPct > aiPct) {
|
|
800
|
+
summaryText += `,加权 AI 影响力 ${weightedPct}%`;
|
|
801
|
+
}
|
|
802
|
+
summaryText += '。';
|
|
803
|
+
this.reportSummary = summaryText;
|
|
804
|
+
this.reportHighlights = [
|
|
805
|
+
{ l: 'AI 主导编辑占比', v: aiPct + '%' },
|
|
806
|
+
{ l: '本月新增提交', v: String(gitStats?.commits || 0) },
|
|
807
|
+
{ l: '节省推理成本', v: '$' + (data.costBreakdown?.cacheSaving || 0).toFixed(2), c: 'var(--forest)' },
|
|
808
|
+
{ l: 'Cache 命中率提升', v: '+17pp', c: 'var(--forest)' },
|
|
809
|
+
{ l: '活跃模型数', v: `${Object.keys(usageStats.models || {}).length} / 12` },
|
|
810
|
+
{ l: '工作仓库数', v: String(Object.keys(usageStats.projects || {}).length) },
|
|
811
|
+
];
|
|
812
|
+
},
|
|
813
|
+
|
|
814
|
+
renderCharts(data) {
|
|
815
|
+
const { usageStats, gitStats, trendData, costBreakdown } = data;
|
|
816
|
+
if (!usageStats || usageStats.requestCount <= 0) {
|
|
817
|
+
destroyAllCharts(['workTypeChart', 'modelChart', 'projectChart', 'toolChart', 'timelineChart', 'commitTypeChart']);
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/* Work Type Pie */
|
|
822
|
+
const scenarioEntries = Object.entries(usageStats.scenarios || {}).filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]);
|
|
823
|
+
renderWorkTypePie('workTypeChart', scenarioEntries);
|
|
824
|
+
|
|
825
|
+
/* Model Bars */
|
|
826
|
+
const modelEntries = Object.entries(usageStats.models || {}).sort((a, b) => b[1].count - a[1].count);
|
|
827
|
+
renderModelBars('modelBarsContainer', modelEntries);
|
|
828
|
+
|
|
829
|
+
/* Project Bars */
|
|
830
|
+
const projEntries = Object.entries(usageStats.projects || {}).filter(([, d]) => d.requests > 0).sort((a, b) => b[1].requests - a[1].requests).slice(0, 8);
|
|
831
|
+
renderProjectBars('projectChart', projEntries);
|
|
832
|
+
|
|
833
|
+
/* Timeline Area */
|
|
834
|
+
if (trendData && Object.keys(trendData.dailyStats || {}).length > 0) {
|
|
835
|
+
renderTimelineArea('timelineChart', trendData);
|
|
836
|
+
} else {
|
|
837
|
+
destroyChart('timelineChart');
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/* Cache is rendered via pure HTML/CSS bars in the new design */
|
|
841
|
+
},
|
|
842
|
+
|
|
843
|
+
/* ── view switching ── */
|
|
844
|
+
openReport() {
|
|
845
|
+
this.view = 'report';
|
|
846
|
+
this.loadReportContent();
|
|
847
|
+
},
|
|
848
|
+
|
|
849
|
+
async loadReportContent() {
|
|
850
|
+
try {
|
|
851
|
+
const params = { tool: this.activeTool, period: this.period, date: this.currentDate, format: 'work', platform: this.reportPlatform, level: this.reportLevel };
|
|
852
|
+
if (this.period === 'custom' && this.customStart && this.customEnd) {
|
|
853
|
+
params.start = this.customStart;
|
|
854
|
+
params.end = this.customEnd;
|
|
855
|
+
}
|
|
856
|
+
if (this.reportProject) {
|
|
857
|
+
params.project = this.reportProject;
|
|
858
|
+
}
|
|
859
|
+
const qs = new URLSearchParams(params).toString();
|
|
860
|
+
const res = await fetch(`/api/report?${qs}`);
|
|
861
|
+
if (!res.ok) return;
|
|
862
|
+
const markdown = await res.text();
|
|
863
|
+
setWorkReportState({ markdown, platform: this.reportPlatform, level: this.reportLevel });
|
|
864
|
+
this.reportHtml = this.renderMarkdownToReportHtml(markdown);
|
|
865
|
+
} catch (e) { console.warn('loadReportContent failed:', e); }
|
|
866
|
+
},
|
|
867
|
+
|
|
868
|
+
setReportLevel(level) {
|
|
869
|
+
this.reportLevel = level;
|
|
870
|
+
this.loadReportContent();
|
|
871
|
+
},
|
|
872
|
+
|
|
873
|
+
setReportPlatform(platform) {
|
|
874
|
+
this.reportPlatform = platform;
|
|
875
|
+
this.loadReportContent();
|
|
876
|
+
},
|
|
877
|
+
|
|
878
|
+
setReportProject(project) {
|
|
879
|
+
this.reportProject = project;
|
|
880
|
+
this.loadReportContent();
|
|
881
|
+
},
|
|
882
|
+
|
|
883
|
+
async copyReport() {
|
|
884
|
+
await copyWorkReport();
|
|
885
|
+
this.copied = true;
|
|
886
|
+
setTimeout(() => this.copied = false, 1400);
|
|
887
|
+
},
|
|
888
|
+
|
|
889
|
+
downloadReport() {
|
|
890
|
+
downloadMarkdown(this.period, this.currentDate);
|
|
891
|
+
},
|
|
892
|
+
|
|
893
|
+
renderMarkdownToReportHtml(md) {
|
|
894
|
+
const lines = md.split('\n');
|
|
895
|
+
const out = [];
|
|
896
|
+
let inTable = false;
|
|
897
|
+
// Security: esc() MUST run first to neutralize HTML, then regex adds safe tags on escaped content
|
|
898
|
+
const inline = s => esc(s).replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>').replace(/`([^`]+)`/g, '<code>$1</code>');
|
|
899
|
+
for (let i = 0; i < lines.length; i++) {
|
|
900
|
+
const line = lines[i];
|
|
901
|
+
if (line.startsWith('|')) {
|
|
902
|
+
if (!inTable) { inTable = true; out.push('<table class="md-table">'); }
|
|
903
|
+
const cells = line.split('|').slice(1, -1).map(c => c.trim());
|
|
904
|
+
if (cells.every(c => /^[-:]+$/.test(c.replace(/\|/g, '')))) continue;
|
|
905
|
+
const tag = inTable && out[out.length - 1] === '<table class="md-table">' ? 'th' : 'td';
|
|
906
|
+
out.push('<tr>' + cells.map(c => `<${tag}>${inline(c)}</${tag}>`).join('') + '</tr>');
|
|
907
|
+
continue;
|
|
908
|
+
} else if (inTable) { inTable = false; out.push('</table>'); }
|
|
909
|
+
if (line.startsWith('# ')) { out.push(`<h1 class="md-h1">${inline(line.slice(2))}</h1>`); continue; }
|
|
910
|
+
if (line.startsWith('## ')) { out.push(`<h2 class="md-h2">${inline(line.slice(3))}</h2>`); continue; }
|
|
911
|
+
if (line.startsWith('### ')) { out.push(`<h3 class="md-h3">${inline(line.slice(4))}</h3>`); continue; }
|
|
912
|
+
if (line.startsWith('- ') || line.startsWith('• ')) { out.push(`<li class="md-li">${inline(line.slice(2))}</li>`); continue; }
|
|
913
|
+
if (/^[━─]+/.test(line.trim()) && line.trim().length >= 5) { out.push(`<div class="md-divider">${inline(line.trim())}</div>`); continue; }
|
|
914
|
+
if (line.trim() === '') { out.push(''); continue; }
|
|
915
|
+
out.push(`<p class="md-p">${inline(line)}</p>`);
|
|
916
|
+
}
|
|
917
|
+
if (inTable) out.push('</table>');
|
|
918
|
+
let html = out.join('\n');
|
|
919
|
+
html = html.replace(/(<li[^>]*>[<\s\S]*?<\/li>\n?)+/g, m => '<ul class="md-ul">\n' + m + '</ul>\n');
|
|
920
|
+
return html;
|
|
921
|
+
},
|
|
922
|
+
|
|
923
|
+
/* ── exports ── */
|
|
924
|
+
exportCSV() { if (this.lastReportData) exportCSV(this.lastReportData, this.period); },
|
|
925
|
+
exportJSON() { if (this.lastReportData) exportJSON(this.lastReportData, this.period); },
|
|
926
|
+
exportHTML() { if (this.lastReportData) exportHTML(this.lastReportData, this.period); },
|
|
927
|
+
printReport() { if (this.lastReportData) printReport(this.lastReportData, this.period); },
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/* ── Register Alpine component ── */
|
|
932
|
+
document.addEventListener('alpine:init', () => {
|
|
933
|
+
Alpine.data('app', appState);
|
|
934
|
+
});
|
|
935
|
+
|
|
936
|
+
/* Dynamic load Alpine after listener is ready */
|
|
937
|
+
const alpineScript = document.createElement('script');
|
|
938
|
+
alpineScript.src = '/vendor/alpine.min.js';
|
|
939
|
+
document.head.appendChild(alpineScript);
|
|
940
|
+
|
|
941
|
+
/* ── Utilities ── */
|
|
942
|
+
function showToast(msg) {
|
|
943
|
+
const toast = document.getElementById(ID.TOAST);
|
|
944
|
+
if (!toast) return;
|
|
945
|
+
toast.textContent = msg;
|
|
946
|
+
toast.style.display = 'block';
|
|
947
|
+
toast.style.opacity = '1';
|
|
948
|
+
setTimeout(() => { toast.style.opacity = '0'; setTimeout(() => { toast.style.display = 'none'; }, 300); }, 3000);
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/* ── Settings Modal ── */
|
|
952
|
+
const SCENARIO_LABELS = { coding: '编码', testing: '测试', debugging: '调试', documentation: '文档', review: '审查', planning: '规划', refactoring: '重构' };
|
|
953
|
+
|
|
954
|
+
function renderKeywordsEditor(keywords) {
|
|
955
|
+
const container = document.getElementById('cfgKeywordsEditor');
|
|
956
|
+
if (!container) return;
|
|
957
|
+
container.innerHTML = '';
|
|
958
|
+
for (const [key, label] of Object.entries(SCENARIO_LABELS)) {
|
|
959
|
+
const words = keywords[key] || [];
|
|
960
|
+
const row = document.createElement('div');
|
|
961
|
+
row.className = 'kw-row';
|
|
962
|
+
row.dataset.key = key;
|
|
963
|
+
|
|
964
|
+
const lbl = document.createElement('div');
|
|
965
|
+
lbl.className = 'kw-label';
|
|
966
|
+
lbl.textContent = label;
|
|
967
|
+
|
|
968
|
+
const tags = document.createElement('div');
|
|
969
|
+
tags.className = 'kw-tags';
|
|
970
|
+
for (const w of words) tags.appendChild(makeKwTag(w));
|
|
971
|
+
|
|
972
|
+
const addWrap = document.createElement('div');
|
|
973
|
+
addWrap.className = 'kw-add-row';
|
|
974
|
+
const addBtn = document.createElement('button');
|
|
975
|
+
addBtn.className = 'kw-add-btn';
|
|
976
|
+
addBtn.textContent = '+';
|
|
977
|
+
addBtn.title = '添加关键词';
|
|
978
|
+
addBtn.onclick = () => {
|
|
979
|
+
addWrap.innerHTML = '';
|
|
980
|
+
const inp = document.createElement('input');
|
|
981
|
+
inp.className = 'kw-add-input';
|
|
982
|
+
inp.placeholder = '关键词';
|
|
983
|
+
const ok = document.createElement('button');
|
|
984
|
+
ok.className = 'kw-add-btn';
|
|
985
|
+
ok.textContent = '确定';
|
|
986
|
+
ok.onclick = () => {
|
|
987
|
+
const v = inp.value.trim();
|
|
988
|
+
if (v && !tags.querySelector('[data-word="' + CSS.escape(v) + '"]')) tags.insertBefore(makeKwTag(v), addWrap);
|
|
989
|
+
resetAddBtn();
|
|
990
|
+
};
|
|
991
|
+
inp.onkeydown = (e) => { if (e.key === 'Enter') ok.click(); if (e.key === 'Escape') resetAddBtn(); };
|
|
992
|
+
addWrap.appendChild(inp);
|
|
993
|
+
addWrap.appendChild(ok);
|
|
994
|
+
inp.focus();
|
|
995
|
+
};
|
|
996
|
+
function resetAddBtn() { addWrap.innerHTML = ''; addWrap.appendChild(addBtn); }
|
|
997
|
+
resetAddBtn();
|
|
998
|
+
|
|
999
|
+
row.appendChild(lbl);
|
|
1000
|
+
row.appendChild(tags);
|
|
1001
|
+
row.appendChild(addWrap);
|
|
1002
|
+
container.appendChild(row);
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
function makeKwTag(word) {
|
|
1007
|
+
const tag = document.createElement('span');
|
|
1008
|
+
tag.className = 'kw-tag';
|
|
1009
|
+
tag.dataset.word = word;
|
|
1010
|
+
tag.textContent = word;
|
|
1011
|
+
const x = document.createElement('span');
|
|
1012
|
+
x.className = 'kw-tag-remove';
|
|
1013
|
+
x.textContent = '×';
|
|
1014
|
+
x.onclick = () => tag.remove();
|
|
1015
|
+
tag.appendChild(x);
|
|
1016
|
+
return tag;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
function collectKeywordsFromEditor() {
|
|
1020
|
+
const result = {};
|
|
1021
|
+
const container = document.getElementById('cfgKeywordsEditor');
|
|
1022
|
+
if (!container) return result;
|
|
1023
|
+
for (const row of container.querySelectorAll('.kw-row')) {
|
|
1024
|
+
const key = row.dataset.key;
|
|
1025
|
+
const words = Array.from(row.querySelectorAll('.kw-tag')).map(t => t.dataset.word);
|
|
1026
|
+
if (words.length > 0) result[key] = words;
|
|
1027
|
+
}
|
|
1028
|
+
// 清洗校验:先 trim 再去重、过滤空串、截断超长词、过滤控制字符
|
|
1029
|
+
for (const [key, words] of Object.entries(result)) {
|
|
1030
|
+
result[key] = [...new Set(words.map(w => w.trim()))]
|
|
1031
|
+
.filter(w => w.length > 0 && w.length <= 50)
|
|
1032
|
+
.filter(w => !/[\x00-\x1f\x7f]/.test(w));
|
|
1033
|
+
}
|
|
1034
|
+
return result;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
window.closeSettings = () => {
|
|
1038
|
+
const modal = document.getElementById('settingsModal');
|
|
1039
|
+
if (modal) modal.style.display = 'none';
|
|
1040
|
+
};
|
|
1041
|
+
|
|
1042
|
+
/* ── Advanced Section Toggle ── */
|
|
1043
|
+
window.toggleKeywordsSection = () => {
|
|
1044
|
+
const section = document.getElementById('cfgKeywordsSection');
|
|
1045
|
+
const btn = document.getElementById('cfgKeywordsToggle');
|
|
1046
|
+
if (!section || !btn) return;
|
|
1047
|
+
const isHidden = section.style.display === 'none';
|
|
1048
|
+
section.style.display = isHidden ? 'block' : 'none';
|
|
1049
|
+
btn.classList.toggle('expanded', isHidden);
|
|
1050
|
+
};
|
|
1051
|
+
|
|
1052
|
+
/* ── Path Tag Editor ── */
|
|
1053
|
+
const FOLDER_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>';
|
|
1054
|
+
const CLOSE_ICON = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
|
|
1055
|
+
|
|
1056
|
+
function renderPathTags(containerId, paths) {
|
|
1057
|
+
const container = document.getElementById(containerId);
|
|
1058
|
+
if (!container) return;
|
|
1059
|
+
container.innerHTML = '';
|
|
1060
|
+
for (let i = 0; i < paths.length; i++) {
|
|
1061
|
+
const tag = document.createElement('div');
|
|
1062
|
+
tag.className = 'path-tag';
|
|
1063
|
+
tag.innerHTML = `
|
|
1064
|
+
<span class="path-tag-icon">${FOLDER_ICON}</span>
|
|
1065
|
+
<span class="path-tag-text" title="${esc(paths[i])}">${esc(paths[i])}</span>
|
|
1066
|
+
<button class="path-tag-remove" onclick="removePathTag('${containerId}', ${i})" title="删除">${CLOSE_ICON}</button>
|
|
1067
|
+
`;
|
|
1068
|
+
container.appendChild(tag);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
function addPathTag(containerId, inputId) {
|
|
1073
|
+
const input = document.getElementById(inputId);
|
|
1074
|
+
const container = document.getElementById(containerId);
|
|
1075
|
+
if (!input || !container) return;
|
|
1076
|
+
const raw = input.value.trim();
|
|
1077
|
+
if (!raw) return;
|
|
1078
|
+
// 支持粘贴多行或多逗号分隔的内容,一次性解析添加
|
|
1079
|
+
const paths = raw.split(/[,,\n\r]+/).map(s => s.trim()).filter(Boolean);
|
|
1080
|
+
const existing = getPathTags(containerId);
|
|
1081
|
+
for (const p of paths) {
|
|
1082
|
+
if (!existing.includes(p)) existing.push(p);
|
|
1083
|
+
}
|
|
1084
|
+
renderPathTags(containerId, existing);
|
|
1085
|
+
input.value = '';
|
|
1086
|
+
input.focus();
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
function removePathTag(containerId, index) {
|
|
1090
|
+
const paths = getPathTags(containerId);
|
|
1091
|
+
paths.splice(index, 1);
|
|
1092
|
+
renderPathTags(containerId, paths);
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
function getPathTags(containerId) {
|
|
1096
|
+
const container = document.getElementById(containerId);
|
|
1097
|
+
if (!container) return [];
|
|
1098
|
+
return Array.from(container.querySelectorAll('.path-tag-text')).map(el => el.textContent);
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
window.openSettings = async () => {
|
|
1102
|
+
const modal = document.getElementById('settingsModal');
|
|
1103
|
+
const hint = document.getElementById('cfgSaveHint');
|
|
1104
|
+
if (hint) { hint.textContent = ''; hint.className = ''; }
|
|
1105
|
+
if (modal) modal.style.display = 'flex';
|
|
1106
|
+
try {
|
|
1107
|
+
const cfg = await fetchConfig();
|
|
1108
|
+
const dirEl = document.getElementById('cfgClaudeDir');
|
|
1109
|
+
if (dirEl) dirEl.value = cfg.claudeDir || '';
|
|
1110
|
+
renderPathTags('cfgReposTags', cfg.repos || []);
|
|
1111
|
+
renderPathTags('cfgExcludeTags', cfg.excludeProjects || []);
|
|
1112
|
+
renderKeywordsEditor(cfg.scenarioKeywords || {});
|
|
1113
|
+
} catch (err) {
|
|
1114
|
+
showToast('加载配置失败: ' + err.message);
|
|
1115
|
+
}
|
|
1116
|
+
};
|
|
1117
|
+
|
|
1118
|
+
document.getElementById('welcomeStartBtn')?.addEventListener('click', async () => {
|
|
1119
|
+
const claudeDir = document.getElementById('welcomeClaudeDir').value.trim();
|
|
1120
|
+
const reposRaw = document.getElementById('welcomeRepos').value.trim();
|
|
1121
|
+
const hint = document.getElementById('welcomeHint');
|
|
1122
|
+
if (!claudeDir) { hint.textContent = '请输入 Claude 日志目录路径'; hint.style.color = 'var(--dest)'; return; }
|
|
1123
|
+
const repos = reposRaw ? reposRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
|
|
1124
|
+
try {
|
|
1125
|
+
hint.textContent = '保存配置中...'; hint.style.color = 'var(--muted-foreground)';
|
|
1126
|
+
await saveConfig({ claudeDir, repos });
|
|
1127
|
+
hint.textContent = '配置已保存,加载数据中...';
|
|
1128
|
+
window.location.reload();
|
|
1129
|
+
} catch (err) { hint.textContent = '保存失败: ' + err.message; hint.style.color = 'var(--dest)'; }
|
|
1130
|
+
});
|
|
1131
|
+
|
|
1132
|
+
window.saveSettings = async () => {
|
|
1133
|
+
const hint = document.getElementById('cfgSaveHint');
|
|
1134
|
+
const scenarioKeywords = collectKeywordsFromEditor();
|
|
1135
|
+
const payload = {
|
|
1136
|
+
claudeDir: document.getElementById('cfgClaudeDir').value.trim(),
|
|
1137
|
+
repos: getPathTags('cfgReposTags'),
|
|
1138
|
+
excludeProjects: getPathTags('cfgExcludeTags'),
|
|
1139
|
+
scenarioKeywords,
|
|
1140
|
+
};
|
|
1141
|
+
try {
|
|
1142
|
+
await saveConfig(payload);
|
|
1143
|
+
if (hint) { hint.textContent = '配置已保存'; hint.className = 'cfg-save-ok'; }
|
|
1144
|
+
setTimeout(() => window.location.reload(), 1200);
|
|
1145
|
+
} catch (err) {
|
|
1146
|
+
if (hint) { hint.textContent = '保存失败: ' + err.message; hint.className = 'cfg-save-err'; }
|
|
1147
|
+
}
|
|
1148
|
+
};
|
|
1149
|
+
|
|
1150
|
+
/* ── Drill-down global handler ── */
|
|
1151
|
+
window._drillHandler = async (type, key, label) => {
|
|
1152
|
+
const modal = document.getElementById(ID.DRILL_MODAL);
|
|
1153
|
+
const title = document.getElementById(ID.DRILL_TITLE);
|
|
1154
|
+
const body = document.getElementById(ID.DRILL_BODY);
|
|
1155
|
+
if (title) title.textContent = label + ' 匹配示例';
|
|
1156
|
+
if (body) body.innerHTML = '<div class="drill-empty">加载中...</div>';
|
|
1157
|
+
if (modal) modal.style.display = 'flex';
|
|
1158
|
+
try {
|
|
1159
|
+
const appEl = document.querySelector('[x-data]');
|
|
1160
|
+
const app = appEl?._x_dataStack?.[0];
|
|
1161
|
+
const period = app?.period || 'daily';
|
|
1162
|
+
const date = app?.currentDate || new Date().toISOString().slice(0, 10);
|
|
1163
|
+
const rows = await fetchDetails({ period, date, dimension: type, key });
|
|
1164
|
+
if (!rows.length) { if (body) body.innerHTML = '<div class="drill-empty">无匹配记录</div>'; return; }
|
|
1165
|
+
if (body) body.innerHTML = '<table class="drill-table"><tr><th>用户消息</th><th>时间</th></tr>' + rows.map(r => `<tr><td class="drill-text" title="${esc(r.text)}">${esc(r.text)}</td><td>${esc(r.timestamp?.slice(0, 16)?.replace('T', ' '))}</td></tr>`).join('') + '</table>';
|
|
1166
|
+
} catch (e) {
|
|
1167
|
+
console.warn('drillHandler failed:', e);
|
|
1168
|
+
if (body) body.innerHTML = '<div class="drill-empty">加载失败</div>';
|
|
1169
|
+
}
|
|
1170
|
+
};
|