@shellui/core 0.7.0 → 0.8.1

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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -1
  3. package/package.json +2 -2
  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/features/storage/StorageBridge.paths.spec.ts +286 -0
  68. package/src/features/storage/StorageBridge.tsx +25 -5
  69. package/src/features/storage/resolveStorageBridgeTarget.spec.ts +51 -0
  70. package/src/features/storage/resolveStorageBridgeTarget.ts +24 -0
  71. package/src/i18n/translations/en/settings.json +201 -0
  72. package/src/i18n/translations/fr/settings.json +201 -0
  73. package/src/index.ts +1 -0
  74. package/src/service-worker/sw.ts +4 -2
@@ -88,6 +88,10 @@ export interface NavigationItem {
88
88
  * Hosting service for this app. Same fallback as `email`.
89
89
  */
90
90
  hosting?: HostingConfig;
91
+ /**
92
+ * AI service for this app. Same fallback as `email`.
93
+ */
94
+ aiService?: AiServiceConfig;
91
95
  }
92
96
 
93
97
  export interface NavigationGroup {
@@ -188,9 +192,13 @@ export interface BackendLoginConfig {
188
192
  /** Same-origin BFF auth for HttpOnly refresh cookies (see docs/features/security.md). */
189
193
  export interface BffAuthConfig {
190
194
  /**
191
- * When true, refresh tokens are stored in an HttpOnly cookie via `/api/auth/*`
192
- * served by the shell host (CLI dev server or your production reverse proxy).
193
- * Default: false (refresh stays in sessionStorage until you enable BFF).
195
+ * Shell-host refresh cookie (`shellui_refresh` on `/api/auth`).
196
+ * `false` turns the routes off. The page then calls identity itself and
197
+ * stores the refresh token in sessionStorage.
198
+ * `true`, or leaving this out, mounts `/api/auth/*` on `shellui start` and
199
+ * `serve:dist`. The page uses them only after `GET /api/auth/session`
200
+ * returns `{ "ready": true }`. A static host without those routes keeps
201
+ * the sessionStorage refresh token.
194
202
  */
195
203
  enabled?: boolean;
196
204
  /** HttpOnly cookie name. Default: `shellui_refresh`. */
@@ -294,8 +302,8 @@ export interface BackendConfig {
294
302
  /** Admin content URL loaded in the admin route view (e.g. "https://example.com/admin"). */
295
303
  adminUrl?: string;
296
304
  /**
297
- * Public origin (or full URL) of this shell — where `/login` and OAuth `/login/callback` live.
298
- * Used by `shellui login`. Not the iframe admin app (`adminUrl`).
305
+ * Public origin (or full URL) of this shell, where `/login` and OAuth `/login/callback` live.
306
+ * The shell allowlists this origin. It is not the iframe admin app (`adminUrl`).
299
307
  * Example: `https://app.example.com` or `http://127.0.0.1:4000`.
300
308
  */
301
309
  loginUrl?: string;
@@ -382,6 +390,24 @@ export interface EmailConfig {
382
390
  showInAdmin?: boolean;
383
391
  }
384
392
 
393
+ /**
394
+ * Optional ai-service wiring for Admin → AI and iframe apps.
395
+ * The shell never invents a URL: without `url`, apps get no ai service.
396
+ */
397
+ export interface AiServiceConfig {
398
+ /**
399
+ * Base URL of ai-service.
400
+ * Required for apps to get AI. There is no built-in default.
401
+ * Local: `http://localhost:8006`.
402
+ */
403
+ url?: string;
404
+ /**
405
+ * When false, hide Admin → AI.
406
+ * Default: true (shown) when `aiService` is set.
407
+ */
408
+ showInAdmin?: boolean;
409
+ }
410
+
385
411
  /**
386
412
  * Custom navigation section for the staff administration panel.
387
413
  * Admin app URL remains `backend.adminUrl` / `backend.adminPathname`.
@@ -460,6 +486,12 @@ export interface ShellUIConfig {
460
486
  * `showInAdmin: false` hides Admin → Email.
461
487
  */
462
488
  email?: EmailConfig;
489
+ /**
490
+ * AI-service connection. Propagated to iframes via SDK settings.
491
+ * Without `url`, the shell sends no ai service (`null`).
492
+ * `showInAdmin: false` hides Admin → AI.
493
+ */
494
+ aiService?: AiServiceConfig;
463
495
  /**
464
496
  * Single theme: built-in name, path to a theme JSON/folder, or inline theme object.
465
497
  * When set without `themes`, only this theme is available in the selector.
@@ -0,0 +1,32 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { MCP_ACTIVITY_ERROR_CODES, type McpActivityErrorCode } from './personalAgentsApi';
3
+ import { MCP_ACTIVITY_ERROR_CODE_I18N_KEYS } from './mcpActivityErrorCodeI18n';
4
+ import en from '../../i18n/translations/en/settings.json';
5
+ import fr from '../../i18n/translations/fr/settings.json';
6
+
7
+ function enLabel(path: string): string {
8
+ const parts = path.split('.');
9
+ let cur: unknown = en;
10
+ for (const p of parts) {
11
+ if (cur === null || cur === undefined || typeof cur !== 'object') return '';
12
+ cur = (cur as Record<string, unknown>)[p];
13
+ }
14
+ return typeof cur === 'string' ? cur : '';
15
+ }
16
+
17
+ describe('MCP_ACTIVITY_ERROR_CODE_I18N_KEYS', () => {
18
+ it('has one non-empty en label per allowlisted code', () => {
19
+ for (const code of MCP_ACTIVITY_ERROR_CODES) {
20
+ const key = MCP_ACTIVITY_ERROR_CODE_I18N_KEYS[code as McpActivityErrorCode];
21
+ expect(key, `missing i18n key mapping for ${code}`).toBeTruthy();
22
+ const label = enLabel(key);
23
+ expect(label.length, `empty en label for ${code} at ${key}`).toBeGreaterThan(0);
24
+ }
25
+ });
26
+
27
+ it('fr keys mirror en structure for errorCode', () => {
28
+ const enErr = en.mcpAgents.activity.detail.errorCode;
29
+ const frErr = fr.mcpAgents.activity.detail.errorCode;
30
+ expect(Object.keys(enErr).sort()).toEqual(Object.keys(frErr).sort());
31
+ });
32
+ });
@@ -0,0 +1,30 @@
1
+ import type { McpActivityErrorCode } from './personalAgentsApi';
2
+
3
+ /**
4
+ * i18n paths under `settings` for each allowlisted identity `error_code`.
5
+ * Keys must cover every `McpActivityErrorCode` (fixed allowlist, not free text).
6
+ */
7
+ export const MCP_ACTIVITY_ERROR_CODE_I18N_KEYS: Record<McpActivityErrorCode, string> = {
8
+ bad_request: 'mcpAgents.activity.detail.errorCode.badRequest',
9
+ unauthorized: 'mcpAgents.activity.detail.errorCode.unauthorized',
10
+ forbidden: 'mcpAgents.activity.detail.errorCode.forbidden',
11
+ not_found: 'mcpAgents.activity.detail.errorCode.notFound',
12
+ conflict: 'mcpAgents.activity.detail.errorCode.conflict',
13
+ rate_limited: 'mcpAgents.activity.detail.errorCode.rateLimited',
14
+ denied: 'mcpAgents.activity.detail.errorCode.denied',
15
+ expired: 'mcpAgents.activity.detail.errorCode.expired',
16
+ timeout: 'mcpAgents.activity.detail.errorCode.timeout',
17
+ upstream_error: 'mcpAgents.activity.detail.errorCode.upstreamError',
18
+ internal_error: 'mcpAgents.activity.detail.errorCode.internalError',
19
+ out_of_sync: 'mcpAgents.activity.detail.errorCode.outOfSync',
20
+ identity_unreachable: 'mcpAgents.activity.detail.errorCode.identityUnreachable',
21
+ identity_unavailable: 'mcpAgents.activity.detail.errorCode.identityUnavailable',
22
+ identity_invalid: 'mcpAgents.activity.detail.errorCode.identityInvalid',
23
+ invalid_grant: 'mcpAgents.activity.detail.errorCode.invalidGrant',
24
+ permission_changed: 'mcpAgents.activity.detail.errorCode.permissionChanged',
25
+ request_expired: 'mcpAgents.activity.detail.errorCode.requestExpired',
26
+ agent_revoked: 'mcpAgents.activity.detail.errorCode.agentRevoked',
27
+ downstream_error: 'mcpAgents.activity.detail.errorCode.downstreamError',
28
+ server_error: 'mcpAgents.activity.detail.errorCode.serverError',
29
+ unknown: 'mcpAgents.activity.detail.errorCode.unknown',
30
+ };
@@ -0,0 +1,91 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { mergeMcpAgentActivity } from './mcpAgentActivityMerge';
3
+ import type { McpAgentActivityRow } from './personalAgentsApi';
4
+
5
+ const row = (overrides: Partial<McpAgentActivityRow>): McpAgentActivityRow => ({
6
+ timestamp: '2026-06-01T00:00:00Z',
7
+ tool: 'storage_list_bucket',
8
+ service: 'storage',
9
+ result: 'ok',
10
+ clientIp: null,
11
+ companyId: '1',
12
+ companyLabel: 'Acme',
13
+ resourceLabel: null,
14
+ operationTitle: null,
15
+ actorLabel: null,
16
+ agentName: null,
17
+ accessKind: 'read',
18
+ durationMs: null,
19
+ outcome: 'allowed',
20
+ approvalRequestId: null,
21
+ errorCode: null,
22
+ ...overrides,
23
+ });
24
+
25
+ describe('mergeMcpAgentActivity', () => {
26
+ const consent = row({
27
+ timestamp: '2026-06-03T00:00:00Z',
28
+ tool: 'oauth.authorize.approved',
29
+ service: 'identity',
30
+ result: 'ok',
31
+ companyLabel: null,
32
+ });
33
+ const device = row({
34
+ timestamp: '2026-05-01T00:00:00Z',
35
+ tool: 'oauth.device.approved',
36
+ service: 'identity',
37
+ result: 'ok',
38
+ });
39
+ const staleCall = row({
40
+ timestamp: '2026-06-02T00:00:00Z',
41
+ tool: 'identity_list_users',
42
+ service: 'identity',
43
+ });
44
+ const newerCall = row({
45
+ timestamp: '2026-06-04T00:00:00Z',
46
+ tool: 'storage_get',
47
+ service: 'storage',
48
+ companyLabel: null,
49
+ });
50
+ const olderCall = row({
51
+ timestamp: '2026-06-02T12:00:00Z',
52
+ tool: 'storage_list_bucket',
53
+ service: 'storage',
54
+ companyLabel: null,
55
+ });
56
+
57
+ it('drops identity call rows, keeps consent, and sorts newest first', () => {
58
+ const merged = mergeMcpAgentActivity([staleCall, device, consent], [olderCall, newerCall], {
59
+ callLogsComplete: true,
60
+ });
61
+ expect(merged.map((item) => item.tool)).toEqual([
62
+ 'storage_get',
63
+ 'oauth.authorize.approved',
64
+ 'storage_list_bucket',
65
+ 'oauth.device.approved',
66
+ ]);
67
+ });
68
+
69
+ it('hides consent older than the loaded call-log page until the list is complete', () => {
70
+ const recentConsent = row({
71
+ timestamp: '2026-06-05T00:00:00Z',
72
+ tool: 'oauth.authorize.approved',
73
+ service: 'identity',
74
+ result: 'ok',
75
+ companyLabel: null,
76
+ });
77
+ const partial = mergeMcpAgentActivity([recentConsent, device], [newerCall], {
78
+ callLogsComplete: false,
79
+ });
80
+ expect(partial.map((item) => item.tool)).toEqual(['oauth.authorize.approved', 'storage_get']);
81
+
82
+ const done = mergeMcpAgentActivity([recentConsent, device], [newerCall], {
83
+ callLogsComplete: true,
84
+ });
85
+ expect(done.map((item) => item.tool)).toEqual([
86
+ 'oauth.authorize.approved',
87
+ 'storage_get',
88
+ 'oauth.device.approved',
89
+ ]);
90
+ });
91
+ });
@@ -0,0 +1,53 @@
1
+ import type { McpAgentActivityRow } from './personalAgentsApi';
2
+
3
+ /**
4
+ * Identity still writes these consent rows. Tool calls moved to ai-service,
5
+ * so other activity rows from identity are older call logs and are dropped.
6
+ */
7
+ const OAUTH_CONSENT_TOOLS = new Set(['oauth.authorize.approved', 'oauth.device.approved']);
8
+
9
+ export function isMcpOAuthConsentActivityRow(row: Pick<McpAgentActivityRow, 'tool'>): boolean {
10
+ return OAUTH_CONSENT_TOOLS.has(row.tool.trim().toLowerCase());
11
+ }
12
+
13
+ function timestampMs(iso: string): number | null {
14
+ const ms = Date.parse(iso);
15
+ return Number.isFinite(ms) ? ms : null;
16
+ }
17
+
18
+ /**
19
+ * Merge OAuth consent rows with ai-service call logs, newest first.
20
+ * While a later call-log page is still unloaded, consent older than the
21
+ * oldest loaded call stays out so it does not jump ahead of that page.
22
+ */
23
+ export function mergeMcpAgentActivity(
24
+ identityRows: McpAgentActivityRow[],
25
+ callLogs: McpAgentActivityRow[],
26
+ options?: { callLogsComplete?: boolean },
27
+ ): McpAgentActivityRow[] {
28
+ const consent = identityRows.filter(isMcpOAuthConsentActivityRow);
29
+ const complete = options?.callLogsComplete !== false;
30
+ let visibleConsent = consent;
31
+ if (!complete && callLogs.length > 0) {
32
+ let oldest = Number.POSITIVE_INFINITY;
33
+ for (const row of callLogs) {
34
+ const ms = timestampMs(row.timestamp);
35
+ if (ms !== null && ms < oldest) oldest = ms;
36
+ }
37
+ if (Number.isFinite(oldest)) {
38
+ visibleConsent = consent.filter((row) => {
39
+ const ms = timestampMs(row.timestamp);
40
+ return ms !== null && ms >= oldest;
41
+ });
42
+ }
43
+ }
44
+
45
+ return [...visibleConsent, ...callLogs].sort((a, b) => {
46
+ const am = timestampMs(a.timestamp);
47
+ const bm = timestampMs(b.timestamp);
48
+ if (am === null && bm === null) return 0;
49
+ if (am === null) return 1;
50
+ if (bm === null) return -1;
51
+ return bm - am;
52
+ });
53
+ }
@@ -0,0 +1,129 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { McpAgentActivityRow } from './personalAgentsApi';
3
+ import {
4
+ buildActivityPrimarySummary,
5
+ formatActivityDurationMs,
6
+ formatActivityResultForDisplay,
7
+ isRecognizedActivityResultToken,
8
+ parseActivityOutcomeFromFields,
9
+ resolveActivityPendingLink,
10
+ } from './mcpAgentActivityPresentation';
11
+
12
+ const baseRow = (overrides: Partial<McpAgentActivityRow> = {}): McpAgentActivityRow => ({
13
+ timestamp: '2026-01-01T12:00:00Z',
14
+ tool: 'storage_get',
15
+ service: 'storage',
16
+ result: 'ok',
17
+ clientIp: null,
18
+ companyId: null,
19
+ companyLabel: null,
20
+ resourceLabel: null,
21
+ operationTitle: null,
22
+ actorLabel: null,
23
+ agentName: null,
24
+ accessKind: null,
25
+ durationMs: null,
26
+ outcome: null,
27
+ approvalRequestId: null,
28
+ errorCode: null,
29
+ ...overrides,
30
+ });
31
+
32
+ const labels = { toolUnknown: 'Unknown tool', operationSuffix: 'Operation' };
33
+
34
+ describe('parseActivityOutcomeFromFields', () => {
35
+ it('prefers parsed outcome from API when set', () => {
36
+ expect(parseActivityOutcomeFromFields('not_allowed', 'denied')).toBe('denied');
37
+ expect(parseActivityOutcomeFromFields('ok', 'allowed')).toBe('allowed');
38
+ });
39
+
40
+ it('uses unknown explicit outcome even when result looks mappable', () => {
41
+ expect(parseActivityOutcomeFromFields('ok', 'unknown')).toBe('unknown');
42
+ });
43
+
44
+ it('maps exact result tokens only when outcome is null', () => {
45
+ expect(parseActivityOutcomeFromFields('ok', null)).toBe('allowed');
46
+ expect(parseActivityOutcomeFromFields('pending_approval', null)).toBe('pending_approval');
47
+ expect(parseActivityOutcomeFromFields('not allowed', null)).toBe('unknown');
48
+ });
49
+ });
50
+
51
+ describe('buildActivityPrimarySummary', () => {
52
+ it('prefers operation_title from API', () => {
53
+ const row = baseRow({
54
+ operationTitle: 'List workspace members',
55
+ tool: 'identity_list_users',
56
+ service: 'identity',
57
+ });
58
+ expect(buildActivityPrimarySummary(row, labels)).toBe('List workspace members');
59
+ });
60
+
61
+ it('uses allowlisted tool label when known', () => {
62
+ const row = baseRow({
63
+ service: 'storage',
64
+ tool: 'storage_delete',
65
+ resourceLabel: 'Reports',
66
+ companyLabel: 'Acme Corp',
67
+ });
68
+ expect(buildActivityPrimarySummary(row, labels)).toBe(
69
+ 'storage Reports: Delete stored object (Acme Corp)',
70
+ );
71
+ });
72
+
73
+ it('falls back to Operation {tool} when not humanized', () => {
74
+ const row = baseRow({
75
+ service: 'identity',
76
+ tool: 'list_users',
77
+ resourceLabel: 'Members',
78
+ });
79
+ expect(buildActivityPrimarySummary(row, labels)).toBe('identity Members: Operation list_users');
80
+ });
81
+ });
82
+
83
+ describe('formatActivityResultForDisplay', () => {
84
+ it('returns token only when recognized', () => {
85
+ expect(formatActivityResultForDisplay('ok')).toBe('ok');
86
+ expect(formatActivityResultForDisplay('PENDING_APPROVAL')).toBe('pending_approval');
87
+ });
88
+
89
+ it('returns null for unrecognized provider strings', () => {
90
+ expect(formatActivityResultForDisplay('upstream said nope')).toBeNull();
91
+ expect(formatActivityResultForDisplay('https://x.test/a?token=1')).toBeNull();
92
+ });
93
+ });
94
+
95
+ describe('isRecognizedActivityResultToken', () => {
96
+ it('flags only allowlisted keys', () => {
97
+ expect(isRecognizedActivityResultToken('ok')).toBe(true);
98
+ expect(isRecognizedActivityResultToken('nope')).toBe(false);
99
+ });
100
+ });
101
+
102
+ describe('formatActivityDurationMs', () => {
103
+ it('returns null for negative or non-finite values', () => {
104
+ expect(formatActivityDurationMs(-1, 'en')).toBeNull();
105
+ expect(formatActivityDurationMs(Number.NaN, 'en')).toBeNull();
106
+ });
107
+ });
108
+
109
+ describe('resolveActivityPendingLink', () => {
110
+ it('returns id link when approval_request_id set', () => {
111
+ const row = baseRow({
112
+ tool: 'storage_delete',
113
+ result: 'pending_approval',
114
+ approvalRequestId: 'ap-1',
115
+ });
116
+ expect(resolveActivityPendingLink(row, new Set())).toEqual({ type: 'id', approvalId: 'ap-1' });
117
+ });
118
+
119
+ it('matches pending outcome to tool name', () => {
120
+ const row = baseRow({
121
+ tool: 'storage_delete',
122
+ result: 'pending_approval',
123
+ });
124
+ expect(resolveActivityPendingLink(row, new Set(['storage_delete']))).toEqual({
125
+ type: 'tool',
126
+ toolName: 'storage_delete',
127
+ });
128
+ });
129
+ });
@@ -0,0 +1,201 @@
1
+ import type {
2
+ McpAgentActivityRow,
3
+ McpActivityAccessKind,
4
+ McpActivityOutcomeKind,
5
+ } from './personalAgentsApi';
6
+ import { humanizeMcpToolName } from './mcpToolActivityRegistry';
7
+
8
+ export type { McpActivityAccessKind, McpActivityOutcomeKind } from './personalAgentsApi';
9
+
10
+ function normalizeResultKey(value: string): string {
11
+ return value
12
+ .trim()
13
+ .toLowerCase()
14
+ .replace(/[\s-]+/g, '_');
15
+ }
16
+
17
+ /** Exact `result` string -> outcome mapping only; unlisted falls back to `outcome` field parsing. */
18
+ const KNOWN_RESULT_OUTCOMES: Record<string, McpActivityOutcomeKind> = {
19
+ ok: 'allowed',
20
+ success: 'allowed',
21
+ allowed: 'allowed',
22
+ allow: 'allowed',
23
+ allow_success: 'allowed',
24
+ allowed_success: 'allowed',
25
+ denied: 'denied',
26
+ forbidden: 'denied',
27
+ failed: 'failed',
28
+ error: 'failed',
29
+ pending: 'pending_approval',
30
+ pending_approval: 'pending_approval',
31
+ awaiting_approval: 'pending_approval',
32
+ waiting_approval: 'pending_approval',
33
+ session: 'session_used',
34
+ session_used: 'session_used',
35
+ unknown: 'unknown',
36
+ };
37
+
38
+ export function parseActivityOutcomeFromFields(
39
+ result: string,
40
+ explicitOutcome: McpActivityOutcomeKind | null | undefined,
41
+ ): McpActivityOutcomeKind {
42
+ if (explicitOutcome !== null && explicitOutcome !== undefined) {
43
+ return explicitOutcome;
44
+ }
45
+
46
+ const r = result.trim();
47
+ if (!r) return 'unknown';
48
+ const exact = KNOWN_RESULT_OUTCOMES[r] ?? KNOWN_RESULT_OUTCOMES[normalizeResultKey(r)];
49
+ return exact ?? 'unknown';
50
+ }
51
+
52
+ export function inferActivityAccessKind(row: McpAgentActivityRow): McpActivityAccessKind {
53
+ return row.accessKind ?? 'unknown';
54
+ }
55
+
56
+ export function formatActivityDurationMs(
57
+ ms: number | null | undefined,
58
+ locale: string,
59
+ ): string | null {
60
+ if (ms === null || ms === undefined || !Number.isFinite(ms) || ms < 0) return null;
61
+ if (ms < 1000) {
62
+ try {
63
+ return `${new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(ms)} ms`;
64
+ } catch {
65
+ return `${Math.round(ms)} ms`;
66
+ }
67
+ }
68
+ const sec = ms / 1000;
69
+ try {
70
+ return `${new Intl.NumberFormat(locale, { maximumFractionDigits: sec < 10 ? 1 : 0 }).format(sec)} s`;
71
+ } catch {
72
+ return `${sec.toFixed(1)} s`;
73
+ }
74
+ }
75
+
76
+ export function formatActivityWhen(iso: string, locale: string): string {
77
+ try {
78
+ return new Intl.DateTimeFormat(locale, {
79
+ dateStyle: 'medium',
80
+ timeStyle: 'short',
81
+ }).format(new Date(iso));
82
+ } catch {
83
+ return iso;
84
+ }
85
+ }
86
+
87
+ export type ActivityPendingLink =
88
+ | { type: 'id'; approvalId: string }
89
+ | { type: 'tool'; toolName: string };
90
+
91
+ export function resolveActivityPendingLink(
92
+ row: McpAgentActivityRow,
93
+ pendingToolNames: Set<string>,
94
+ ): ActivityPendingLink | null {
95
+ if (row.approvalRequestId?.trim()) {
96
+ return { type: 'id', approvalId: row.approvalRequestId.trim() };
97
+ }
98
+ const outcome = parseActivityOutcomeFromFields(row.result, row.outcome);
99
+ if (outcome !== 'pending_approval') return null;
100
+ const tool = row.tool.trim();
101
+ if (!tool) return null;
102
+ if (pendingToolNames.has(tool)) return { type: 'tool', toolName: tool };
103
+ return null;
104
+ }
105
+
106
+ export type ActivitySummaryLabels = {
107
+ toolUnknown: string;
108
+ operationSuffix: string;
109
+ };
110
+
111
+ export function buildActivityPrimarySummary(
112
+ row: McpAgentActivityRow,
113
+ labels: ActivitySummaryLabels,
114
+ ): string {
115
+ const title = row.operationTitle?.trim();
116
+ if (title) {
117
+ return title;
118
+ }
119
+
120
+ const rawTool = row.tool.trim();
121
+ const service = row.service.trim() || 'service';
122
+ const resource = row.resourceLabel?.trim();
123
+ const company = row.companyLabel?.trim();
124
+ const registry = rawTool ? humanizeMcpToolName(rawTool) : null;
125
+ const op = rawTool ? `${labels.operationSuffix} ${rawTool}` : labels.operationSuffix;
126
+ const toolLine = registry ?? (rawTool ? op : labels.toolUnknown);
127
+
128
+ const parts: string[] = [];
129
+ if (resource) {
130
+ parts.push(`${service} ${resource}: ${toolLine}`);
131
+ } else {
132
+ parts.push(`${service}: ${toolLine}`);
133
+ }
134
+ if (company) parts.push(`(${company})`);
135
+ return parts.join(' ');
136
+ }
137
+
138
+ const APPROVAL_OUTCOME_LABEL_KEYS: Record<string, string> = {
139
+ pending: 'mcpAgents.activity.detail.approvalOutcomeValue.pending',
140
+ denied: 'mcpAgents.activity.detail.approvalOutcomeValue.denied',
141
+ accepted: 'mcpAgents.activity.detail.approvalOutcomeValue.accepted',
142
+ session_used: 'mcpAgents.activity.detail.approvalOutcomeValue.sessionUsed',
143
+ expired: 'mcpAgents.activity.detail.approvalOutcomeValue.expired',
144
+ failed: 'mcpAgents.activity.detail.approvalOutcomeValue.failed',
145
+ };
146
+
147
+ const SAFE_TOKEN = /^[a-z0-9_]{1,32}$/;
148
+ const SAFE_WRAPPER_TOOL = /^[A-Za-z0-9_.-]{1,64}$/;
149
+
150
+ /** Translated label key for a known approval outcome. Unknown tokens return null. */
151
+ export function activityApprovalOutcomeLabelKey(value: string | null | undefined): string | null {
152
+ if (!value?.trim()) return null;
153
+ const token = normalizeResultKey(value);
154
+ if (!SAFE_TOKEN.test(token)) return null;
155
+ return APPROVAL_OUTCOME_LABEL_KEYS[token] ?? null;
156
+ }
157
+
158
+ /** Safe raw token when the outcome has no translated label. */
159
+ export function activityApprovalOutcomeFallback(value: string | null | undefined): string | null {
160
+ if (!value?.trim()) return null;
161
+ const token = normalizeResultKey(value);
162
+ if (!SAFE_TOKEN.test(token) || APPROVAL_OUTCOME_LABEL_KEYS[token]) return null;
163
+ return token;
164
+ }
165
+
166
+ /** Wrapper name safe to show after "via". */
167
+ export function activityWrapperToolForDisplay(value: string | null | undefined): string | null {
168
+ const text = value?.trim() ?? '';
169
+ if (!SAFE_WRAPPER_TOOL.test(text)) return null;
170
+ return text;
171
+ }
172
+
173
+ /** Single-line redacted error text. Control characters are stripped. */
174
+ export function activityErrorMessageForDisplay(value: string | null | undefined): string | null {
175
+ if (!value) return null;
176
+ const text = value
177
+ .replace(/[\u0000-\u001F\u007F]+/g, ' ')
178
+ .replace(/\s+/g, ' ')
179
+ .trim();
180
+ if (!text) return null;
181
+ return text.slice(0, 500);
182
+ }
183
+
184
+ export function isRecognizedActivityResultToken(raw: string | null | undefined): boolean {
185
+ if (!raw?.trim()) return false;
186
+ const r = raw.trim();
187
+ return (
188
+ Object.prototype.hasOwnProperty.call(KNOWN_RESULT_OUTCOMES, r) ||
189
+ Object.prototype.hasOwnProperty.call(KNOWN_RESULT_OUTCOMES, normalizeResultKey(r))
190
+ );
191
+ }
192
+
193
+ /**
194
+ * Returns a display token only for recognized provider result codes. Never returns arbitrary text.
195
+ */
196
+ export function formatActivityResultForDisplay(raw: string | null | undefined): string | null {
197
+ if (!raw?.trim()) return null;
198
+ const trimmed = raw.trim();
199
+ if (!isRecognizedActivityResultToken(trimmed)) return null;
200
+ return KNOWN_RESULT_OUTCOMES[trimmed] !== undefined ? trimmed : normalizeResultKey(trimmed);
201
+ }