-
Notifications
You must be signed in to change notification settings - Fork 508
Expand file tree
/
Copy pathtimeseries-queries.service.spec.ts
More file actions
390 lines (347 loc) 路 13.6 KB
/
Copy pathtimeseries-queries.service.spec.ts
File metadata and controls
390 lines (347 loc) 路 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { TimeseriesQueriesService } from './timeseries-queries.service';
import { AgentMessage } from '../../entities/agent-message.entity';
import { Agent } from '../../entities/agent.entity';
import { TenantCacheService } from '../../common/services/tenant-cache.service';
describe('TimeseriesQueriesService', () => {
let service: TimeseriesQueriesService;
let mockGetRawMany: jest.Mock;
let mockGetMany: jest.Mock;
let mockTurnQb: {
select: jest.Mock;
addSelect: jest.Mock;
leftJoin: jest.Mock;
where: jest.Mock;
andWhere: jest.Mock;
orWhere: jest.Mock;
groupBy: jest.Mock;
addGroupBy: jest.Mock;
orderBy: jest.Mock;
addOrderBy: jest.Mock;
limit: jest.Mock;
getRawMany: jest.Mock;
getRawOne: jest.Mock;
getMany: jest.Mock;
};
beforeEach(async () => {
mockGetRawMany = jest.fn().mockResolvedValue([]);
mockGetMany = jest.fn().mockResolvedValue([]);
mockTurnQb = {
select: jest.fn().mockReturnThis(),
addSelect: jest.fn().mockReturnThis(),
leftJoin: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
andWhere: jest.fn().mockReturnThis(),
orWhere: jest.fn().mockReturnThis(),
groupBy: jest.fn().mockReturnThis(),
addGroupBy: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
addOrderBy: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
getRawMany: mockGetRawMany,
getRawOne: jest.fn().mockResolvedValue({}),
getMany: mockGetMany,
};
const mockAgentQb = {
select: jest.fn().mockReturnThis(),
addSelect: jest.fn().mockReturnThis(),
leftJoin: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
andWhere: jest.fn().mockReturnThis(),
orWhere: jest.fn().mockReturnThis(),
groupBy: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
getMany: mockGetMany,
getRawMany: mockGetRawMany,
};
const module: TestingModule = await Test.createTestingModule({
providers: [
TimeseriesQueriesService,
{
provide: getRepositoryToken(AgentMessage),
useValue: { createQueryBuilder: jest.fn().mockReturnValue(mockTurnQb) },
},
{
provide: getRepositoryToken(Agent),
useValue: { createQueryBuilder: jest.fn().mockReturnValue(mockAgentQb) },
},
{
provide: TenantCacheService,
useValue: { resolve: jest.fn().mockResolvedValue('tenant-123') },
},
],
}).compile();
service = module.get<TimeseriesQueriesService>(TimeseriesQueriesService);
});
describe('getActiveSkills', () => {
it('maps DB rows with status field', async () => {
mockGetRawMany.mockResolvedValue([
{
name: 'deploy',
agent_name: 'bot-1',
run_count: 5,
last_active_at: '2026-02-16T10:00:00',
},
]);
const result = await service.getActiveSkills('24h', 'u1');
expect(result[0]).toEqual({
name: 'deploy',
agent_name: 'bot-1',
run_count: 5,
last_active_at: '2026-02-16T10:00:00',
status: 'active',
});
});
it('returns null agent_name when not present', async () => {
mockGetRawMany.mockResolvedValue([
{ name: 'scan', agent_name: null, run_count: 1, last_active_at: '2026-02-16' },
]);
const result = await service.getActiveSkills('24h', 'u1');
expect(result[0].agent_name).toBeNull();
});
});
describe('getCostByModel', () => {
it('computes share_pct for each model', async () => {
mockGetRawMany.mockResolvedValue([
{ model: 'claude-opus-4-6', tokens: 700, estimated_cost: 10.0, auth_type: 'subscription' },
{ model: 'gpt-4o', tokens: 300, estimated_cost: 5.0, auth_type: 'api_key' },
]);
const result = await service.getCostByModel('7d', 'u1');
expect(result).toHaveLength(2);
expect(result[0].share_pct).toBe(70);
expect(result[1].share_pct).toBe(30);
expect(result[0].auth_type).toBe('subscription');
expect(result[1].auth_type).toBe('api_key');
});
it('returns display_name from model_pricing when available', async () => {
mockGetRawMany.mockResolvedValue([
{
model: 'gpt-4o',
display_name: 'GPT-4o',
tokens: 500,
estimated_cost: 2.0,
auth_type: null,
},
]);
const result = await service.getCostByModel('7d', 'u1');
expect(result[0].display_name).toBe('GPT-4o');
});
it('falls back to model slug when display_name is missing', async () => {
mockGetRawMany.mockResolvedValue([
{ model: 'custom-model', tokens: 100, estimated_cost: 1.0, auth_type: null },
]);
const result = await service.getCostByModel('7d', 'u1');
expect(result[0].display_name).toBe('custom-model');
});
it('returns 0 share_pct when total tokens is 0', async () => {
mockGetRawMany.mockResolvedValue([{ model: 'test', tokens: 0, estimated_cost: 0 }]);
const result = await service.getCostByModel('7d', 'u1');
expect(result[0].share_pct).toBe(0);
expect(result[0].auth_type).toBeNull();
});
});
describe('getRecentActivity', () => {
it('returns raw query results', async () => {
const fakeRows = [{ id: '1', timestamp: '2026-02-16', agent_name: 'bot-1' }];
mockGetRawMany.mockResolvedValue(fakeRows);
expect(await service.getRecentActivity('24h', 'u1')).toEqual(fakeRows);
});
it('returns empty array when no activity', async () => {
mockGetRawMany.mockResolvedValue([]);
expect(await service.getRecentActivity('24h', 'u1', 10)).toEqual([]);
});
it('propagates specificity_category rows returned by the helper projection', async () => {
mockGetRawMany.mockResolvedValue([
{
id: '1',
timestamp: '2026-02-16T10:00:00',
agent_name: 'bot-1',
model: 'claude-opus-4-6',
routing_tier: 'standard',
routing_reason: 'specificity',
specificity_category: 'coding',
},
]);
const rows = (await service.getRecentActivity('24h', 'u1')) as Array<Record<string, unknown>>;
expect(rows[0]!['specificity_category']).toBe('coding');
});
it('projects specificity_category through the shared helper (regression: dashboard badge drift)', async () => {
mockGetRawMany.mockResolvedValue([]);
await service.getRecentActivity('24h', 'u1');
const projectedAliases = [
...mockTurnQb.select.mock.calls.map((call) => call[1]),
...mockTurnQb.addSelect.mock.calls.map((call) => call[1]),
];
expect(projectedAliases).toContain('specificity_category');
expect(projectedAliases).toContain('routing_tier');
expect(projectedAliases).toContain('routing_reason');
});
});
describe('getTimeseries', () => {
it('returns merged token, cost, and message timeseries for hourly', async () => {
mockGetRawMany.mockResolvedValue([
{ hour: '2026-02-16T10:00:00', input_tokens: 100, output_tokens: 50, cost: 1.5, count: 5 },
{ hour: '2026-02-16T11:00:00', input_tokens: 200, output_tokens: 80, cost: 2.0, count: 8 },
]);
const result = await service.getTimeseries('24h', 'u1', true, 'tenant-123');
expect(result.tokenUsage).toHaveLength(2);
expect(result.costUsage).toHaveLength(2);
expect(result.messageUsage).toHaveLength(2);
expect(result.tokenUsage[0]).toEqual({
hour: '2026-02-16T10:00:00',
input_tokens: 100,
output_tokens: 50,
});
expect(result.costUsage[1]).toEqual({ hour: '2026-02-16T11:00:00', cost: 2.0 });
expect(result.messageUsage[0]).toEqual({ hour: '2026-02-16T10:00:00', count: 5 });
});
it('returns merged timeseries for daily buckets', async () => {
mockGetRawMany.mockResolvedValue([
{ date: '2026-02-15', input_tokens: 500, output_tokens: 300, cost: 5.0, count: 20 },
]);
const result = await service.getTimeseries('7d', 'u1', false, 'tenant-123');
expect(result.tokenUsage).toHaveLength(1);
expect(result.tokenUsage[0]).toEqual({
date: '2026-02-15',
input_tokens: 500,
output_tokens: 300,
});
expect(result.costUsage[0]).toEqual({ date: '2026-02-15', cost: 5.0 });
expect(result.messageUsage[0]).toEqual({ date: '2026-02-15', count: 20 });
});
it('returns empty arrays when no data', async () => {
mockGetRawMany.mockResolvedValue([]);
const result = await service.getTimeseries('24h', 'u1', true, 'tenant-123');
expect(result.tokenUsage).toEqual([]);
expect(result.costUsage).toEqual([]);
expect(result.messageUsage).toEqual([]);
});
it('defaults null values to 0', async () => {
mockGetRawMany.mockResolvedValue([
{
hour: '2026-02-16T10:00:00',
input_tokens: null,
output_tokens: null,
cost: null,
count: null,
},
]);
const result = await service.getTimeseries('24h', 'u1', true);
expect(result.tokenUsage[0]).toEqual({
hour: '2026-02-16T10:00:00',
input_tokens: 0,
output_tokens: 0,
});
expect(result.costUsage[0]).toEqual({ hour: '2026-02-16T10:00:00', cost: 0 });
expect(result.messageUsage[0]).toEqual({ hour: '2026-02-16T10:00:00', count: 0 });
});
it('passes agentName to tenant filter', async () => {
mockGetRawMany.mockResolvedValue([]);
const result = await service.getTimeseries('24h', 'u1', true, 'tenant-123', 'bot-1');
expect(result.tokenUsage).toEqual([]);
});
});
describe('getAgentList', () => {
it('returns agents with sparkline data and display_name', async () => {
mockGetMany.mockResolvedValueOnce([
{ name: 'bot-1', display_name: 'Bot One', created_at: '2026-02-16' },
]);
mockGetRawMany
.mockResolvedValueOnce([
{
agent_name: 'bot-1',
message_count: 10,
last_active: '2026-02-16',
total_cost: 5.0,
total_tokens: 1000,
},
])
.mockResolvedValueOnce([
{ agent_name: 'bot-1', date: '2026-02-15', tokens: 100 },
{ agent_name: 'bot-1', date: '2026-02-16', tokens: 200 },
]);
const result = await service.getAgentList('u1');
expect(result).toHaveLength(1);
expect(result[0].agent_name).toBe('bot-1');
expect(result[0].display_name).toBe('Bot One');
expect(result[0].sparkline).toBeDefined();
expect(result[0].total_cost).toBe(5.0);
});
it('falls back to agent_name when display_name is null', async () => {
mockGetMany.mockResolvedValueOnce([
{ name: 'bot-1', display_name: null, created_at: '2026-02-16' },
]);
mockGetRawMany
.mockResolvedValueOnce([
{
agent_name: 'bot-1',
message_count: 10,
last_active: '2026-02-16',
total_cost: 5.0,
total_tokens: 1000,
},
])
.mockResolvedValueOnce([]);
const result = await service.getAgentList('u1');
expect(result[0].display_name).toBe('bot-1');
});
it('returns empty sparkline for agent with no spark data', async () => {
mockGetMany.mockResolvedValueOnce([
{ name: 'lonely-bot', display_name: null, created_at: '2026-02-16' },
]);
mockGetRawMany
.mockResolvedValueOnce([
{
agent_name: 'lonely-bot',
message_count: 1,
last_active: '2026-02-16',
total_cost: 0,
total_tokens: 0,
},
])
.mockResolvedValueOnce([]);
const result = await service.getAgentList('u1');
expect(result[0].sparkline).toEqual([]);
});
it('returns agent with zero stats when no telemetry exists', async () => {
mockGetMany.mockResolvedValueOnce([
{ name: 'new-bot', display_name: null, created_at: '2026-02-16' },
]);
mockGetRawMany.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
const result = await service.getAgentList('u1');
expect(result).toHaveLength(1);
expect(result[0].agent_name).toBe('new-bot');
expect(result[0].display_name).toBe('new-bot');
expect(result[0].message_count).toBe(0);
expect(result[0].total_cost).toBe(0);
expect(result[0].sparkline).toEqual([]);
});
/**
* The Settings page loads the current override from GET /api/v1/agents
* (to prefill the Auto/Custom radio). If this projection ever drops the
* field, the Settings page silently reverts to "Auto" every reload.
*/
it('surfaces a configured context_floor_override on each agent row', async () => {
mockGetMany.mockResolvedValueOnce([
{
name: 'custom-bot',
display_name: null,
created_at: '2026-02-16',
context_floor_override: 50_000,
},
]);
mockGetRawMany.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
const result = await service.getAgentList('u1');
expect(result[0].context_floor_override).toBe(50_000);
});
it('defaults context_floor_override to null when the agent row has no override', async () => {
mockGetMany.mockResolvedValueOnce([
{ name: 'auto-bot', display_name: null, created_at: '2026-02-16' },
]);
mockGetRawMany.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
const result = await service.getAgentList('u1');
expect(result[0].context_floor_override).toBeNull();
});
});
});