@shellui/core 0.7.0-beta.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -0
  3. package/package.json +3 -3
  4. package/schemas/shellui.config.schema.json +45 -2
  5. package/src/app.tsx +2 -0
  6. package/src/features/auth/AuthProvider.tsx +212 -97
  7. package/src/features/auth/appBackend/configSchema.spec.ts +1 -0
  8. package/src/features/auth/appBackend/frameAuth.ts +5 -0
  9. package/src/features/auth/backends/shellui.spec.ts +110 -0
  10. package/src/features/auth/backends/shellui.ts +47 -20
  11. package/src/features/auth/backends/types.ts +5 -0
  12. package/src/features/auth/hooks/useAuth.tsx +6 -1
  13. package/src/features/auth/types.ts +5 -0
  14. package/src/features/auth/utils/bffAuthClient.spec.ts +313 -0
  15. package/src/features/auth/utils/bffAuthClient.ts +171 -49
  16. package/src/features/auth/utils/buildSessionFromParams.ts +5 -2
  17. package/src/features/auth/utils/buildSessionFromTokenPayload.spec.ts +12 -0
  18. package/src/features/auth/utils/buildSessionFromTokenPayload.ts +3 -1
  19. package/src/features/auth/utils/canRestoreStoredSession.spec.ts +140 -4
  20. package/src/features/auth/utils/canRestoreStoredSession.ts +47 -0
  21. package/src/features/auth/utils/cliCallback.ts +5 -0
  22. package/src/features/auth/utils/identityBrowserLogout.spec.ts +185 -0
  23. package/src/features/auth/utils/identityBrowserLogout.ts +174 -0
  24. package/src/features/auth/utils/index.ts +21 -3
  25. package/src/features/auth/utils/isBffAuthEnabled.ts +10 -2
  26. package/src/features/auth/utils/normalizeAuthSettings.spec.ts +9 -0
  27. package/src/features/auth/utils/normalizeAuthSettings.ts +3 -1
  28. package/src/features/auth/utils/pkce.spec.ts +29 -1
  29. package/src/features/auth/utils/pkce.ts +106 -2
  30. package/src/features/config/types.ts +37 -5
  31. package/src/features/mcp/mcpActivityErrorCodeI18n.spec.ts +32 -0
  32. package/src/features/mcp/mcpActivityErrorCodeI18n.ts +30 -0
  33. package/src/features/mcp/mcpAgentActivityMerge.spec.ts +91 -0
  34. package/src/features/mcp/mcpAgentActivityMerge.ts +53 -0
  35. package/src/features/mcp/mcpAgentActivityPresentation.spec.ts +129 -0
  36. package/src/features/mcp/mcpAgentActivityPresentation.ts +201 -0
  37. package/src/features/mcp/mcpAgentsConnect.spec.ts +215 -0
  38. package/src/features/mcp/mcpAgentsConnect.ts +189 -0
  39. package/src/features/mcp/mcpToolActivityRegistry.spec.ts +9 -0
  40. package/src/features/mcp/mcpToolActivityRegistry.ts +20 -0
  41. package/src/features/mcp/mcpToolApprovalsApi.spec.ts +113 -0
  42. package/src/features/mcp/mcpToolApprovalsApi.ts +162 -0
  43. package/src/features/mcp/personalAgentsApi.spec.ts +661 -0
  44. package/src/features/mcp/personalAgentsApi.ts +697 -0
  45. package/src/features/settings/SettingsIcons.tsx +28 -0
  46. package/src/features/settings/SettingsRoutes.tsx +8 -0
  47. package/src/features/settings/SettingsView.tsx +90 -26
  48. package/src/features/settings/components/McpAgentActivitySection.spec.tsx +255 -0
  49. package/src/features/settings/components/McpAgentActivitySection.tsx +481 -0
  50. package/src/features/settings/components/McpAgents.spec.tsx +336 -0
  51. package/src/features/settings/components/McpAgents.tsx +654 -0
  52. package/src/features/settings/components/McpPendingApprovals.spec.tsx +201 -0
  53. package/src/features/settings/components/McpPendingApprovals.tsx +168 -0
  54. package/src/features/settings/components/McpPersonalStatusPrefetch.tsx +21 -0
  55. package/src/features/settings/hooks/useMcpPendingToolApprovals.ts +69 -0
  56. package/src/features/settings/hooks/useMcpPersonalStatus.ts +83 -0
  57. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +44 -1
  58. package/src/features/settings/utils/buildSettingsForPropagation.ts +30 -1
  59. package/src/features/settings/utils/isMcpAgentsSettingsEligible.spec.ts +25 -0
  60. package/src/features/settings/utils/isMcpAgentsSettingsEligible.ts +14 -0
  61. package/src/features/settings/utils/loadMcpPersonalStatus.spec.ts +76 -0
  62. package/src/features/settings/utils/loadMcpPersonalStatus.ts +84 -0
  63. package/src/features/settings/utils/mcpPersonalStatusCache.spec.ts +77 -0
  64. package/src/features/settings/utils/mcpPersonalStatusCache.ts +95 -0
  65. package/src/features/settings/utils/shouldShowMcpAgentsSettings.spec.ts +66 -0
  66. package/src/features/settings/utils/shouldShowMcpAgentsSettings.ts +16 -0
  67. package/src/i18n/translations/en/settings.json +201 -0
  68. package/src/i18n/translations/fr/settings.json +201 -0
  69. package/src/index.ts +1 -0
  70. package/src/service-worker/sw.ts +4 -2
@@ -0,0 +1,661 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import type { ShellUIConfig } from '../config/types';
3
+ import {
4
+ createMcpPersonalAgent,
5
+ fetchMcpPersonalAgentCallLogs,
6
+ fetchMcpPersonalAgents,
7
+ fetchMcpPersonalStatus,
8
+ getMcpPersonalCompanyId,
9
+ getShellIdentityBackendUrl,
10
+ McpCallLogUnavailableError,
11
+ parseCreatePersonalAgentResult,
12
+ parseMcpAgentList,
13
+ parseMcpAgentActivity,
14
+ parseMcpAgentSummary,
15
+ parseMcpCallLogActivityRow,
16
+ parseMcpPersonalStatus,
17
+ parseStrictMcpActivityErrorCode,
18
+ parseStrictMcpActivityOutcome,
19
+ parseValidatedGlobalMcpEndpointUrl,
20
+ revokeMcpPersonalAgent,
21
+ MCP_ACTIVITY_ERROR_CODES,
22
+ } from './personalAgentsApi';
23
+
24
+ describe('getShellIdentityBackendUrl', () => {
25
+ it('returns a trimmed shellui backend url', () => {
26
+ expect(
27
+ getShellIdentityBackendUrl({
28
+ backend: { type: 'shellui', url: ' https://id.example.com/ ' },
29
+ } as ShellUIConfig),
30
+ ).toBe('https://id.example.com');
31
+ });
32
+
33
+ it('returns null for non-shellui backends', () => {
34
+ expect(
35
+ getShellIdentityBackendUrl({ backend: { type: 'other', url: 'x' } } as ShellUIConfig),
36
+ ).toBe(null);
37
+ });
38
+ });
39
+
40
+ describe('getMcpPersonalCompanyId', () => {
41
+ it('uses numeric company id from config', () => {
42
+ expect(
43
+ getMcpPersonalCompanyId({
44
+ backend: { type: 'shellui', url: 'x', companyId: 42 },
45
+ } as ShellUIConfig),
46
+ ).toBe('42');
47
+ });
48
+ });
49
+
50
+ describe('parseValidatedGlobalMcpEndpointUrl', () => {
51
+ it('accepts https origin + /mcp only', () => {
52
+ expect(parseValidatedGlobalMcpEndpointUrl('https://dash.example.com/mcp')).toBe(
53
+ 'https://dash.example.com/mcp',
54
+ );
55
+ expect(parseValidatedGlobalMcpEndpointUrl('https://dash.example.com/mcp/')).toBe(
56
+ 'https://dash.example.com/mcp',
57
+ );
58
+ });
59
+
60
+ it('accepts http localhost global MCP for local development', () => {
61
+ expect(parseValidatedGlobalMcpEndpointUrl('http://127.0.0.1:8080/mcp')).toBe(
62
+ 'http://127.0.0.1:8080/mcp',
63
+ );
64
+ });
65
+
66
+ it('rejects bare origin, double path, queries, and non-http(s)', () => {
67
+ expect(parseValidatedGlobalMcpEndpointUrl('https://dash.example.com')).toBeNull();
68
+ expect(parseValidatedGlobalMcpEndpointUrl('https://dash.example.com/mcp/mcp')).toBeNull();
69
+ expect(parseValidatedGlobalMcpEndpointUrl('https://dash.example.com/mcp?x=1')).toBeNull();
70
+ expect(parseValidatedGlobalMcpEndpointUrl('ftp://dash.example.com/mcp')).toBeNull();
71
+ expect(parseValidatedGlobalMcpEndpointUrl('https://user@dash.example.com/mcp')).toBeNull();
72
+ });
73
+ });
74
+
75
+ describe('parseMcpPersonalStatus', () => {
76
+ it('parses enabled status and url', () => {
77
+ expect(
78
+ parseMcpPersonalStatus({ mcp_enabled: true, mcp_url: 'https://ai.test/c/1/mcp' }),
79
+ ).toEqual({ mcpEnabled: true, mcpUrl: 'https://ai.test/c/1/mcp', globalMcpUrl: null });
80
+ });
81
+
82
+ it('parses global_mcp_url when present', () => {
83
+ expect(
84
+ parseMcpPersonalStatus({
85
+ mcp_enabled: true,
86
+ mcp_url: null,
87
+ global_mcp_url: 'https://dash.example.com/mcp',
88
+ }),
89
+ ).toEqual({ mcpEnabled: true, mcpUrl: null, globalMcpUrl: 'https://dash.example.com/mcp' });
90
+ });
91
+
92
+ it('drops invalid global_mcp_url', () => {
93
+ expect(
94
+ parseMcpPersonalStatus({
95
+ mcp_enabled: true,
96
+ mcp_url: null,
97
+ global_mcp_url: 'https://dash.example.com',
98
+ }),
99
+ ).toEqual({ mcpEnabled: true, mcpUrl: null, globalMcpUrl: null });
100
+ });
101
+
102
+ it('parses global_identity when present', () => {
103
+ expect(
104
+ parseMcpPersonalStatus({
105
+ mcp_enabled: true,
106
+ mcp_url: null,
107
+ global_identity: false,
108
+ }),
109
+ ).toEqual({ mcpEnabled: true, mcpUrl: null, globalMcpUrl: null, globalIdentity: false });
110
+ });
111
+
112
+ it('returns null for invalid payloads', () => {
113
+ expect(parseMcpPersonalStatus({ mcp_enabled: 'yes' })).toBeNull();
114
+ });
115
+ });
116
+
117
+ describe('parseMcpAgentSummary', () => {
118
+ const row = {
119
+ id: 'a1',
120
+ kind: 'personal',
121
+ name: 'CLI',
122
+ access_mode: 'ask',
123
+ read_level: 'safe',
124
+ allow_destructive_without_asking: false,
125
+ services_allowed: ['identity', 'ai'],
126
+ expires_at: '2026-12-01T00:00:00Z',
127
+ paused_at: null,
128
+ revoked_at: null,
129
+ is_active: true,
130
+ created_at: '2026-01-01T00:00:00Z',
131
+ oauth_client_id: null,
132
+ personal_token_id: 'pt-1',
133
+ };
134
+
135
+ it('maps snake_case fields', () => {
136
+ expect(parseMcpAgentSummary(row)).toMatchObject({
137
+ id: 'a1',
138
+ kind: 'personal',
139
+ accessMode: 'ask',
140
+ readLevel: 'safe',
141
+ servicesAllowed: ['identity', 'ai'],
142
+ personalTokenId: 'pt-1',
143
+ });
144
+ });
145
+ });
146
+
147
+ describe('parseMcpAgentList', () => {
148
+ it('filters invalid rows', () => {
149
+ expect(parseMcpAgentList({ agents: [{ id: 'x' }, null] })).toEqual([]);
150
+ });
151
+ });
152
+
153
+ describe('parseStrictMcpActivityOutcome', () => {
154
+ it('maps only exact normalized tokens', () => {
155
+ expect(parseStrictMcpActivityOutcome('allowed')).toBe('allowed');
156
+ expect(parseStrictMcpActivityOutcome('Denied')).toBe('denied');
157
+ expect(parseStrictMcpActivityOutcome('waiting_approval')).toBe('pending_approval');
158
+ expect(parseStrictMcpActivityOutcome('not-a-known-outcome')).toBeNull();
159
+ });
160
+ });
161
+
162
+ describe('parseStrictMcpActivityErrorCode', () => {
163
+ it('accepts fixed allowlist only', () => {
164
+ for (const code of MCP_ACTIVITY_ERROR_CODES) {
165
+ expect(parseStrictMcpActivityErrorCode(code)).toBe(code);
166
+ expect(parseStrictMcpActivityErrorCode(code.toUpperCase())).toBe(code);
167
+ }
168
+ expect(parseStrictMcpActivityErrorCode('custom_failure')).toBeNull();
169
+ });
170
+
171
+ it('drops injection-shaped keys that are not allowlisted tokens', () => {
172
+ expect(parseStrictMcpActivityErrorCode("'; DROP TABLE activity; --")).toBeNull();
173
+ });
174
+ });
175
+
176
+ describe('parseMcpAgentActivity', () => {
177
+ it('maps optional enrichment fields', () => {
178
+ const parsed = parseMcpAgentActivity({
179
+ agent_id: 'a1',
180
+ activity: [
181
+ {
182
+ timestamp: '2026-01-01T00:00:00Z',
183
+ tool: 'x',
184
+ service: 'identity',
185
+ result: 'ok',
186
+ outcome: 'allowed',
187
+ access_kind: 'read',
188
+ duration_ms: 42,
189
+ resource_label: 'Members',
190
+ operation_title: 'List members',
191
+ company_name: 'Acme',
192
+ actor: 'staff@example.com',
193
+ agent_name: 'My bot',
194
+ approval_request_id: 'ap-9',
195
+ error_code: 'downstream_error',
196
+ error_message:
197
+ 'Exception: https://evil.example/nonce token=secret-key https://x.test?token=1',
198
+ },
199
+ ],
200
+ });
201
+ expect(parsed?.activity[0]).toMatchObject({
202
+ outcome: 'allowed',
203
+ accessKind: 'read',
204
+ durationMs: 42,
205
+ resourceLabel: 'Members',
206
+ operationTitle: 'List members',
207
+ companyLabel: 'Acme',
208
+ actorLabel: 'staff@example.com',
209
+ agentName: 'My bot',
210
+ approvalRequestId: 'ap-9',
211
+ errorCode: 'downstream_error',
212
+ });
213
+ });
214
+
215
+ it('ignores error_message and does not retain it on the row', () => {
216
+ const parsed = parseMcpAgentActivity({
217
+ agent_id: 'a1',
218
+ activity: [
219
+ {
220
+ timestamp: '2026-01-01T00:00:00Z',
221
+ tool: 'x',
222
+ service: 'identity',
223
+ result: 'failed',
224
+ outcome: 'failed',
225
+ error_code: 'internal_error',
226
+ error_message: 'forbidden upstream text with https://evil.example',
227
+ },
228
+ ],
229
+ });
230
+ expect(parsed?.activity[0]).toMatchObject({ errorCode: 'internal_error' });
231
+ expect(parsed?.activity[0]).not.toHaveProperty('errorDetailRaw');
232
+ expect(parsed?.activity[0]).not.toHaveProperty('errorMessage');
233
+ });
234
+
235
+ it('treats negative duration_ms as not reported', () => {
236
+ const parsed = parseMcpAgentActivity({
237
+ agent_id: 'a1',
238
+ activity: [
239
+ {
240
+ timestamp: '2026-01-01T00:00:00Z',
241
+ tool: 'x',
242
+ service: 'identity',
243
+ result: 'ok',
244
+ duration_ms: -5,
245
+ },
246
+ ],
247
+ });
248
+ expect(parsed?.activity[0]?.durationMs).toBeNull();
249
+ });
250
+
251
+ it('drops unrecognized outcome strings', () => {
252
+ const parsed = parseMcpAgentActivity({
253
+ agent_id: 'a1',
254
+ activity: [
255
+ {
256
+ timestamp: '2026-01-01T12:00:00Z',
257
+ tool: 'x',
258
+ service: 'identity',
259
+ result: 'custom_vendor_code',
260
+ outcome: 'vendor_says_maybe',
261
+ },
262
+ ],
263
+ });
264
+ expect(parsed?.activity[0]?.outcome).toBeNull();
265
+ });
266
+
267
+ it('parses error_code and ignores invalid error_code', () => {
268
+ const ok = parseMcpAgentActivity({
269
+ agent_id: 'a1',
270
+ activity: [
271
+ {
272
+ timestamp: '2026-01-01T12:00:00Z',
273
+ tool: 'x',
274
+ service: 'identity',
275
+ result: 'failed',
276
+ outcome: 'failed',
277
+ error_code: 'identity_unreachable',
278
+ },
279
+ ],
280
+ });
281
+ expect(ok?.activity[0]).toMatchObject({
282
+ errorCode: 'identity_unreachable',
283
+ outcome: 'failed',
284
+ });
285
+
286
+ const bad = parseMcpAgentActivity({
287
+ agent_id: 'a1',
288
+ activity: [
289
+ {
290
+ timestamp: '2026-01-01T12:00:00Z',
291
+ tool: 'x',
292
+ service: 'identity',
293
+ result: 'failed',
294
+ outcome: 'failed',
295
+ error_code: 'vendor_oops',
296
+ },
297
+ ],
298
+ });
299
+ expect(bad?.activity[0]).toMatchObject({ errorCode: null });
300
+ });
301
+ });
302
+
303
+ describe('parseCreatePersonalAgentResult', () => {
304
+ it('parses create response', () => {
305
+ const agent = {
306
+ id: 'a1',
307
+ kind: 'personal',
308
+ name: 'CLI',
309
+ access_mode: 'read_only',
310
+ read_level: 'safe',
311
+ allow_destructive_without_asking: false,
312
+ services_allowed: ['identity'],
313
+ expires_at: null,
314
+ paused_at: null,
315
+ revoked_at: null,
316
+ is_active: true,
317
+ created_at: '2026-01-01T00:00:00Z',
318
+ oauth_client_id: null,
319
+ personal_token_id: 'p1',
320
+ };
321
+ expect(
322
+ parseCreatePersonalAgentResult({
323
+ agent,
324
+ access_token: 'secret',
325
+ token_type: 'bearer',
326
+ expires_at: '2026-02-01T00:00:00Z',
327
+ resource: 'https://ai.test/c/1/mcp',
328
+ }),
329
+ ).toMatchObject({
330
+ accessToken: 'secret',
331
+ tokenType: 'bearer',
332
+ resource: 'https://ai.test/c/1/mcp',
333
+ });
334
+ });
335
+ });
336
+
337
+ describe('mcp personal fetch helpers', () => {
338
+ afterEach(() => {
339
+ vi.unstubAllGlobals();
340
+ });
341
+
342
+ it('fetchMcpPersonalStatus sends bearer and company_id', async () => {
343
+ const fetchMock = vi.fn().mockResolvedValue({
344
+ ok: true,
345
+ json: async () => ({
346
+ mcp_enabled: true,
347
+ mcp_url: 'https://ai.test/c/1/mcp',
348
+ global_mcp_url: null,
349
+ }),
350
+ });
351
+ vi.stubGlobal('fetch', fetchMock);
352
+
353
+ const status = await fetchMcpPersonalStatus('https://id.example.com', 'tok', '7');
354
+ expect(status.mcpEnabled).toBe(true);
355
+ expect(status.globalMcpUrl).toBeNull();
356
+ expect(fetchMock).toHaveBeenCalledOnce();
357
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
358
+ expect(url).toBe('https://id.example.com/api/v1/mcp/personal/status?company_id=7');
359
+ expect(init.headers).toMatchObject({ Authorization: 'Bearer tok' });
360
+ });
361
+
362
+ it('createMcpPersonalAgent strips saas unless allowSaas is true', async () => {
363
+ const agent = {
364
+ id: 'a1',
365
+ kind: 'personal',
366
+ name: 'CLI',
367
+ access_mode: 'ask',
368
+ read_level: 'safe',
369
+ allow_destructive_without_asking: false,
370
+ services_allowed: ['identity'],
371
+ expires_at: '2026-12-01T00:00:00Z',
372
+ paused_at: null,
373
+ revoked_at: null,
374
+ is_active: true,
375
+ created_at: '2026-01-01T00:00:00Z',
376
+ oauth_client_id: null,
377
+ personal_token_id: 'p1',
378
+ };
379
+ const fetchMock = vi.fn().mockResolvedValue({
380
+ ok: true,
381
+ json: async () => ({
382
+ agent,
383
+ access_token: 'once',
384
+ token_type: 'bearer',
385
+ expires_at: '2026-12-01T00:00:00Z',
386
+ resource: 'https://ai.test/c/1/mcp',
387
+ }),
388
+ });
389
+ vi.stubGlobal('fetch', fetchMock);
390
+
391
+ const input = {
392
+ name: 'CLI',
393
+ services: ['identity', 'saas'] as const,
394
+ accessMode: 'ask' as const,
395
+ readLevel: 'safe' as const,
396
+ allowDestructive: false,
397
+ expiresAt: '2026-12-01T00:00:00Z',
398
+ };
399
+
400
+ await createMcpPersonalAgent('https://id.example.com', 'tok', '1', {
401
+ ...input,
402
+ services: [...input.services],
403
+ });
404
+ let body = JSON.parse(String((fetchMock.mock.calls[0] as [string, RequestInit])[1].body));
405
+ expect(body.services).toEqual(['identity']);
406
+
407
+ fetchMock.mockClear();
408
+ await createMcpPersonalAgent(
409
+ 'https://id.example.com',
410
+ 'tok',
411
+ '1',
412
+ {
413
+ ...input,
414
+ services: [...input.services],
415
+ },
416
+ { allowSaas: true },
417
+ );
418
+ body = JSON.parse(String((fetchMock.mock.calls[0] as [string, RequestInit])[1].body));
419
+ expect(body.services).toEqual(['identity', 'saas']);
420
+ });
421
+
422
+ it('createMcpPersonalAgent posts snake_case body', async () => {
423
+ const agent = {
424
+ id: 'a1',
425
+ kind: 'personal',
426
+ name: 'CLI',
427
+ access_mode: 'ask',
428
+ read_level: 'safe',
429
+ allow_destructive_without_asking: false,
430
+ services_allowed: ['identity'],
431
+ expires_at: '2026-12-01T00:00:00Z',
432
+ paused_at: null,
433
+ revoked_at: null,
434
+ is_active: true,
435
+ created_at: '2026-01-01T00:00:00Z',
436
+ oauth_client_id: null,
437
+ personal_token_id: 'p1',
438
+ };
439
+ const fetchMock = vi.fn().mockResolvedValue({
440
+ ok: true,
441
+ json: async () => ({
442
+ agent,
443
+ access_token: 'once',
444
+ token_type: 'bearer',
445
+ expires_at: '2026-12-01T00:00:00Z',
446
+ resource: 'https://ai.test/c/1/mcp',
447
+ }),
448
+ });
449
+ vi.stubGlobal('fetch', fetchMock);
450
+
451
+ await createMcpPersonalAgent('https://id.example.com', 'tok', '1', {
452
+ name: 'CLI',
453
+ services: ['identity'],
454
+ accessMode: 'ask',
455
+ readLevel: 'safe',
456
+ allowDestructive: false,
457
+ expiresAt: '2026-12-01T00:00:00Z',
458
+ });
459
+
460
+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
461
+ expect(JSON.parse(String(init.body))).toEqual({
462
+ name: 'CLI',
463
+ services: ['identity'],
464
+ access_mode: 'ask',
465
+ read_level: 'safe',
466
+ allow_destructive: false,
467
+ expires_at: '2026-12-01T00:00:00Z',
468
+ });
469
+ });
470
+
471
+ it('fetchMcpPersonalAgents parses list', async () => {
472
+ const fetchMock = vi.fn().mockResolvedValue({
473
+ ok: true,
474
+ json: async () => ({ agents: [] }),
475
+ });
476
+ vi.stubGlobal('fetch', fetchMock);
477
+ await expect(fetchMcpPersonalAgents('https://id.example.com', 'tok', '')).resolves.toEqual([]);
478
+ });
479
+
480
+ it('revokeMcpPersonalAgent posts to revoke path', async () => {
481
+ const agent = {
482
+ id: 'a1',
483
+ kind: 'personal',
484
+ name: 'CLI',
485
+ access_mode: 'ask',
486
+ read_level: 'safe',
487
+ allow_destructive_without_asking: false,
488
+ services_allowed: ['identity'],
489
+ expires_at: null,
490
+ paused_at: null,
491
+ revoked_at: '2026-02-01T00:00:00Z',
492
+ is_active: false,
493
+ created_at: '2026-01-01T00:00:00Z',
494
+ oauth_client_id: null,
495
+ personal_token_id: 'p1',
496
+ };
497
+ const fetchMock = vi.fn().mockResolvedValue({
498
+ ok: true,
499
+ json: async () => ({ agent }),
500
+ });
501
+ vi.stubGlobal('fetch', fetchMock);
502
+
503
+ const revoked = await revokeMcpPersonalAgent('https://id.example.com', 'tok', '1', 'a1');
504
+ expect(revoked.revokedAt).toBeTruthy();
505
+ const [url] = fetchMock.mock.calls[0] as [string];
506
+ expect(url).toContain('/api/v1/mcp/personal/agents/a1/revoke');
507
+ });
508
+ });
509
+
510
+ const callLogRow = {
511
+ id: 'log-1',
512
+ company_id: 42,
513
+ agent_id: 'agent-1',
514
+ agent_name: 'Laptop',
515
+ client_id: 'client-1',
516
+ client_name: 'Cursor',
517
+ token_kind: 'oauth',
518
+ user_id: 7,
519
+ user_email: 'dev@example.com',
520
+ service: 'storage',
521
+ tool_name: 'storage_list_bucket',
522
+ wrapper_tool: 'ai_call_tool',
523
+ operation_title: 'List bucket',
524
+ access_kind: 'read',
525
+ outcome: 'failed',
526
+ resource_label: 'Reports',
527
+ arguments: { bucket: 'reports' },
528
+ status: 'error',
529
+ status_code: 502,
530
+ error_code: 'downstream_error',
531
+ error_message: 'Upstream timed out',
532
+ duration_ms: 18,
533
+ approval_id: 'ap-9',
534
+ approval_channel: 'form',
535
+ approval_outcome: 'accepted',
536
+ created_at: '2026-06-02T00:00:00Z',
537
+ };
538
+
539
+ describe('parseMcpCallLogActivityRow', () => {
540
+ it('maps ai-service fields onto the activity row', () => {
541
+ expect(parseMcpCallLogActivityRow(callLogRow)).toMatchObject({
542
+ timestamp: '2026-06-02T00:00:00Z',
543
+ tool: 'storage_list_bucket',
544
+ service: 'storage',
545
+ companyId: '42',
546
+ companyLabel: null,
547
+ clientIp: null,
548
+ actorLabel: 'dev@example.com',
549
+ agentName: 'Laptop',
550
+ approvalRequestId: 'ap-9',
551
+ errorCode: 'downstream_error',
552
+ errorMessage: 'Upstream timed out',
553
+ wrapperTool: 'ai_call_tool',
554
+ approvalOutcome: 'accepted',
555
+ outcome: 'failed',
556
+ durationMs: 18,
557
+ });
558
+ });
559
+
560
+ it('treats an empty error_code as absent and maps waiting_approval', () => {
561
+ const row = parseMcpCallLogActivityRow({
562
+ ...callLogRow,
563
+ outcome: 'waiting_approval',
564
+ status: 'waiting_approval',
565
+ error_code: '',
566
+ error_message: '',
567
+ approval_id: '',
568
+ wrapper_tool: '',
569
+ approval_outcome: '',
570
+ });
571
+ expect(row).toMatchObject({
572
+ outcome: 'pending_approval',
573
+ errorCode: null,
574
+ approvalRequestId: null,
575
+ });
576
+ expect(row).not.toHaveProperty('errorMessage');
577
+ expect(row).not.toHaveProperty('wrapperTool');
578
+ expect(row).not.toHaveProperty('approvalOutcome');
579
+ expect(row?.companyLabel).toBeNull();
580
+ expect(row?.clientIp).toBeNull();
581
+ });
582
+ });
583
+
584
+ describe('fetchMcpPersonalAgentCallLogs', () => {
585
+ afterEach(() => {
586
+ vi.unstubAllGlobals();
587
+ });
588
+
589
+ it('treats 404 as an empty page', async () => {
590
+ const fetchMock = vi.fn().mockResolvedValue({
591
+ ok: false,
592
+ status: 404,
593
+ json: async () => ({ error: 'Not found.' }),
594
+ });
595
+ vi.stubGlobal('fetch', fetchMock);
596
+
597
+ await expect(
598
+ fetchMcpPersonalAgentCallLogs('https://ai.example/', 'tok', 'agent 1', { offset: 0 }),
599
+ ).resolves.toEqual({
600
+ count: 0,
601
+ limit: 50,
602
+ offset: 0,
603
+ callLogs: [],
604
+ });
605
+
606
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
607
+ expect(url).toBe(
608
+ 'https://ai.example/ai/v1/mcp/personal/agents/agent%201/call-logs?limit=50&offset=0',
609
+ );
610
+ expect(url).not.toContain('company_id');
611
+ expect(init.headers).toMatchObject({ Authorization: 'Bearer tok' });
612
+ });
613
+
614
+ it('requests the next page with offset', async () => {
615
+ const fetchMock = vi
616
+ .fn()
617
+ .mockResolvedValueOnce({
618
+ ok: true,
619
+ status: 200,
620
+ json: async () => ({
621
+ count: 60,
622
+ limit: 50,
623
+ offset: 0,
624
+ call_logs: [callLogRow],
625
+ }),
626
+ })
627
+ .mockResolvedValueOnce({
628
+ ok: true,
629
+ status: 200,
630
+ json: async () => ({
631
+ count: 60,
632
+ limit: 50,
633
+ offset: 50,
634
+ call_logs: [{ ...callLogRow, id: 'log-2', tool_name: 'storage_get' }],
635
+ }),
636
+ });
637
+ vi.stubGlobal('fetch', fetchMock);
638
+
639
+ const first = await fetchMcpPersonalAgentCallLogs('http://localhost:8006', 'tok', 'agent-1');
640
+ expect(first.callLogs).toHaveLength(1);
641
+ expect(first.count).toBe(60);
642
+
643
+ const second = await fetchMcpPersonalAgentCallLogs('http://localhost:8006', 'tok', 'agent-1', {
644
+ offset: first.offset + first.limit,
645
+ });
646
+ expect(second.callLogs[0]?.tool).toBe('storage_get');
647
+ const [firstUrl] = fetchMock.mock.calls[0] as [string];
648
+ const [secondUrl] = fetchMock.mock.calls[1] as [string];
649
+ expect(firstUrl).toContain('offset=0');
650
+ expect(secondUrl).toContain('offset=50');
651
+ expect(secondUrl).toContain('/ai/v1/mcp/personal/agents/agent-1/call-logs');
652
+ });
653
+
654
+ it('throws when ai-service is unreachable', async () => {
655
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')));
656
+
657
+ await expect(
658
+ fetchMcpPersonalAgentCallLogs('http://localhost:8006', 'tok', 'agent-1'),
659
+ ).rejects.toBeInstanceOf(McpCallLogUnavailableError);
660
+ });
661
+ });