@bevel-software/platform-core-frontend 0.35.0 → 0.36.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 (75) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +40 -97
  3. package/src/core/KnowledgeSurface.tsx +92 -0
  4. package/src/core/__tests__/CoreAppShell.root-claims.test.tsx +280 -0
  5. package/src/core/registry.ts +110 -2
  6. package/src/index.ts +3 -0
  7. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +1 -1
  8. package/src/modules/access/hooks/useFileAccess.ts +1 -1
  9. package/src/modules/audit/components/principal-grouping.ts +49 -49
  10. package/src/modules/change-requests/__tests__/ChangeRequestDialog.sync-banner.test.tsx +1 -1
  11. package/src/modules/change-requests/__tests__/FileChangeBoxes.test.tsx +6 -6
  12. package/src/modules/change-requests/__tests__/apply-outcome-for-every-viewer.test.tsx +8 -8
  13. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +1 -1
  14. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +1 -1
  15. package/src/modules/git/__tests__/GitSyncFailedBanner.test.tsx +1 -1
  16. package/src/modules/git/__tests__/pr.api.test.ts +3 -3
  17. package/src/modules/git/components/FileHistoryPanel.tsx +1 -1
  18. package/src/modules/git/components/GitSyncFailedBanner.tsx +1 -1
  19. package/src/modules/git/services/git.api.ts +1 -1
  20. package/src/modules/git/services/pr-prompts.ts +1 -1
  21. package/src/modules/layout/state/layout.context.ts +8 -0
  22. package/src/modules/library/__tests__/SkillPage.test.tsx +5 -5
  23. package/src/modules/library/__tests__/ToolConnectionSection.test.tsx +11 -0
  24. package/src/modules/library/__tests__/ToolVarRow.test.tsx +109 -0
  25. package/src/modules/library/components/tool-page/ToolVarRow.tsx +86 -19
  26. package/src/modules/library/services/library.api.ts +2 -2
  27. package/src/modules/onboarding/__tests__/onboarding.test.tsx +8 -8
  28. package/src/modules/onboarding/state/agent-connection.ts +1 -1
  29. package/src/modules/pr/services/pr-merge.api.ts +1 -1
  30. package/src/modules/pr/services/pr-open.api.ts +1 -1
  31. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +96 -30
  32. package/src/modules/secrets-vault/components/IncludeToggle.tsx +29 -0
  33. package/src/modules/secrets-vault/components/ManagedConnectorCard.tsx +189 -0
  34. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.managed.test.tsx +212 -0
  35. package/src/modules/secrets-vault/components/__tests__/ManagedConnectorCard.test.tsx +182 -0
  36. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +3 -0
  37. package/src/modules/secrets-vault/components/__tests__/ToolSecretsPanel.test.tsx +1 -0
  38. package/src/modules/secrets-vault/components/__tests__/connect-lists-what-the-banner-counted.test.tsx +1 -0
  39. package/src/modules/secrets-vault/index.ts +2 -0
  40. package/src/modules/secrets-vault/probe/__tests__/probe-verdict.test.ts +1 -0
  41. package/src/modules/secrets-vault/services/connect.api.ts +46 -5
  42. package/src/modules/secrets-vault/services/tool-secrets.api.ts +21 -3
  43. package/src/modules/secrets-vault/utils/managed-card-state.ts +61 -0
  44. package/src/modules/setup/utils/__tests__/root-folders.test.ts +5 -1
  45. package/src/modules/setup/utils/root-folders.ts +2 -2
  46. package/src/modules/toolbar/components/Toolbar.tsx +1 -1
  47. package/src/modules/{workflow → version-control}/hooks/__tests__/useFileLock.test.tsx +10 -10
  48. package/src/modules/{workflow → version-control}/hooks/__tests__/useFileLock.wire.test.tsx +1 -1
  49. package/src/modules/{workflow → version-control}/hooks/useEventBusSubscription.ts +2 -2
  50. package/src/modules/{workflow → version-control}/hooks/useFileLock.ts +1 -1
  51. package/src/modules/{workflow → version-control}/index.ts +2 -2
  52. package/src/modules/{workflow → version-control}/services/__tests__/lock.api.test.ts +1 -1
  53. package/src/modules/{workflow → version-control}/state/EventBusProvider.tsx +6 -6
  54. package/src/modules/{workflow → version-control}/state/event-bus.context.ts +4 -4
  55. package/src/modules/workspace/components/FileExplorer.tsx +96 -41
  56. package/src/modules/workspace/components/FileRoute.tsx +24 -1
  57. package/src/modules/workspace/components/FileViewer.tsx +1 -1
  58. package/src/modules/workspace/components/KbPageHeader.tsx +1 -1
  59. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +159 -13
  60. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +50 -2
  61. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +5 -5
  62. package/src/modules/workspace/components/renderers/__tests__/ImageRenderer.test.tsx +5 -5
  63. package/src/modules/workspace/hooks/__tests__/useImageRevision.test.tsx +9 -9
  64. package/src/modules/workspace/hooks/__tests__/useWorkspaceImageResolver.test.tsx +7 -7
  65. package/src/modules/workspace/hooks/useImageRevision.ts +1 -1
  66. package/src/modules/workspace/hooks/useWorkspaceState.ts +2 -2
  67. package/src/modules/workspace/state/__tests__/applied-request-clears-pending.test.tsx +9 -9
  68. package/src/modules/workspace/utils/__tests__/fileTree.test.ts +9 -1
  69. package/src/modules/workspace/utils/fileTree.ts +10 -2
  70. package/src/modules/workspace/utils/treeConfirm.ts +1 -1
  71. /package/src/modules/{workflow → version-control}/services/lock.api.ts +0 -0
  72. /package/src/modules/{workflow → version-control}/state/ChangeRequestStaleBinder.tsx +0 -0
  73. /package/src/modules/{workflow → version-control}/state/EventBusFocusBinder.tsx +0 -0
  74. /package/src/modules/{workflow → version-control}/state/__tests__/EventBusProvider.storage.test.tsx +0 -0
  75. /package/src/modules/{workflow → version-control}/state/__tests__/EventBusProvider.watch.test.tsx +0 -0
@@ -0,0 +1,189 @@
1
+ import { useState } from 'react';
2
+ import { Link } from 'react-router-dom';
3
+ import { Badge, Button, Surface, TextField } from '../../../shared/components';
4
+ import { cn } from '../../../lib/utils';
5
+ import { pathForTool } from '../../library';
6
+ // A component is composed from its file, never from a module's entry (the
7
+ // Module Map: entries carry utilities and contracts; a component re-export
8
+ // is an import cycle waiting to happen).
9
+ import { ToolLogo } from '../../library/components/ToolLogo';
10
+ import { IncludeToggle } from './IncludeToggle';
11
+ import { canStartSignIn, managedCardState, type ManagedCardState, type ManagedToolOAuth } from '../utils/managed-card-state';
12
+
13
+ /**
14
+ * One managed connector on the Connect page: what connecting lets Hexis do,
15
+ * the permissions it asks for in plain words, and the one control the
16
+ * reader has — Connect, Reconnect or Disconnect. A workspace connection
17
+ * (one an owner makes for everyone) shows the same card to everyone and
18
+ * offers the controls only to a writer of the tool. The states, and what
19
+ * each means, are `managedCardState`'s; the words for each are below.
20
+ */
21
+ const STATE_BADGE: Record<ManagedCardState, { text: string; tone: 'ok' | 'wait' | 'outline' | 'danger' }> = {
22
+ unavailable: { text: 'Not available yet', tone: 'outline' },
23
+ 'owner-only': { text: 'Needs an owner', tone: 'outline' },
24
+ ready: { text: 'Ready to connect', tone: 'wait' },
25
+ // "Signed in", not "Connected": the card knows a token is stored, as every
26
+ // sign-in row on this page does. "Connected" is the one word reserved for
27
+ // a real call's answer (the key probe), and it is said in one place only.
28
+ connected: { text: 'Signed in', tone: 'ok' },
29
+ 'needs-reconnect': { text: 'Needs reconnect', tone: 'wait' },
30
+ };
31
+
32
+ export interface ManagedConnectorCardProps {
33
+ o: ManagedToolOAuth;
34
+ busy: boolean;
35
+ onConnect: () => void;
36
+ onDisconnect: () => void;
37
+ /** An owner brings the deployment's own OAuth app in place of the managed one. */
38
+ onOwnApp?: (clientId: string, clientSecret: string) => Promise<void>;
39
+ /**
40
+ * The include/skip position, as every sign-in row on the page carries it:
41
+ * what the agent may use. With `onToggle`, the card shows the same control
42
+ * the rows do; a skipped card is greyed and offers Include and nothing else.
43
+ */
44
+ on?: boolean;
45
+ onToggle?: () => void;
46
+ }
47
+
48
+ export function ManagedConnectorCard({ o, busy, onConnect, onDisconnect, onOwnApp, on = true, onToggle }: ManagedConnectorCardProps) {
49
+ const m = o.managed;
50
+ const state = managedCardState(o);
51
+ const skipped = onToggle !== undefined && !on;
52
+ const badge = skipped ? { text: 'Skipped', tone: 'outline' as const } : STATE_BADGE[state];
53
+ const dim = skipped || state === 'unavailable' || state === 'owner-only';
54
+ // Connect and Reconnect need a way to open a sign-in (the broker, or an
55
+ // owner's own app) and a reader allowed to; Disconnect needs only a
56
+ // stored token the reader may remove. `ownerOnly` is the server's word on
57
+ // the second part, in every state: a reader sees a workspace connection's
58
+ // state and none of its controls.
59
+ const canStart = canStartSignIn(o) && !o.ownerOnly;
60
+ const canDisconnect = o.authorized && !o.ownerOnly;
61
+ const shared = m.tokenScope === 'shared';
62
+ const [ownAppOpen, setOwnAppOpen] = useState(false);
63
+ return (
64
+ <Surface tone="surface" radius="xl" elevation="card" padded data-testid={`connector-${m.connectorId}`}>
65
+ <div className="flex items-center gap-2.5">
66
+ {onToggle && <IncludeToggle on={on} busy={busy} onChange={onToggle} />}
67
+ <ToolLogo slug={o.slug} name={m.displayName} className={cn(dim ? 'grayscale' : undefined)} />
68
+ <Link
69
+ to={pathForTool(o.slug)}
70
+ aria-label={`Open ${m.displayName}`}
71
+ className={cn('truncate text-ui font-semibold hover:underline', dim ? 'text-ink-faint' : 'text-ink')}
72
+ >
73
+ {m.displayName}
74
+ </Link>
75
+ <Badge tone={badge.tone} size="xs" className="shrink-0">
76
+ {!skipped && state === 'connected' && m.account ? `Signed in as ${m.account}` : badge.text}
77
+ </Badge>
78
+ <span className="ml-auto flex shrink-0 items-center gap-1.5">
79
+ {skipped ? (
80
+ // Put back the way a skipped row is: the box beside the name does
81
+ // the same, and an unticked box in a greyed card reads as a record
82
+ // of what happened, not as the way to undo it.
83
+ <Button variant="outline" size="tiny" disabled={busy} onClick={onToggle}>
84
+ Include
85
+ </Button>
86
+ ) : (
87
+ <>
88
+ {canDisconnect && (
89
+ <Button variant="quiet" size="tiny" disabled={busy} onClick={onDisconnect}>
90
+ Disconnect
91
+ </Button>
92
+ )}
93
+ {canStart && (
94
+ <Button variant={state === 'connected' ? 'outline' : 'primary'} size="tiny" disabled={busy} onClick={onConnect}>
95
+ {state === 'connected' || state === 'needs-reconnect' ? 'Reconnect' : 'Connect'}
96
+ </Button>
97
+ )}
98
+ </>
99
+ )}
100
+ </span>
101
+ </div>
102
+ <p className="mt-2 text-detail text-ink-muted">{m.description}</p>
103
+ {m.permissions.length > 0 && (
104
+ <ul className="mt-2 list-disc pl-5 text-detail text-ink-muted">
105
+ {m.permissions.map((p) => (
106
+ <li key={p}>{p}</li>
107
+ ))}
108
+ </ul>
109
+ )}
110
+ <p className="mt-2 text-detail text-ink-faint">
111
+ {shared ? 'One connection for the whole workspace, made by a tool owner.' : 'You connect your own account.'}
112
+ {/* Why a sign-in cannot start here, each cause in its own words: a
113
+ workspace connection with an own app pinned is refused that app,
114
+ which only the owner can remove; no broker is the admin's to fix. */}
115
+ {!canStartSignIn(o) &&
116
+ (shared && m.ownApp
117
+ ? ' This workspace connection has your organisation’s own app pinned, which it cannot use: a tool owner removes the client secret to connect it through the managed connector.'
118
+ : ' This deployment is not connected to a connector broker yet; ask your admin.')}
119
+ {m.ownApp && !shared && ' Signing in through your organisation’s own app.'}
120
+ </p>
121
+ {onOwnApp && (
122
+ <div className="mt-2">
123
+ {ownAppOpen ? (
124
+ <OwnAppForm
125
+ onCancel={() => setOwnAppOpen(false)}
126
+ onSave={async (id, secret) => {
127
+ await onOwnApp(id, secret);
128
+ setOwnAppOpen(false);
129
+ }}
130
+ />
131
+ ) : (
132
+ <Button variant="quiet" size="tiny" onClick={() => setOwnAppOpen(true)}>
133
+ {m.ownApp ? 'Replace our own app' : 'Use our own app instead'}
134
+ </Button>
135
+ )}
136
+ </div>
137
+ )}
138
+ </Surface>
139
+ );
140
+ }
141
+
142
+ /**
143
+ * "Use our own app": a regulated customer registers its own OAuth app with
144
+ * the provider (redirect URI: this deployment's `/api/secrets/oauth/callback`)
145
+ * and pins it here. From then on the sign-in runs from this deployment, not
146
+ * the broker. Write-only, like every secret field on this page.
147
+ */
148
+ function OwnAppForm({
149
+ onSave,
150
+ onCancel,
151
+ }: {
152
+ onSave: (clientId: string, clientSecret: string) => Promise<void>;
153
+ onCancel: () => void;
154
+ }) {
155
+ const [clientId, setClientId] = useState('');
156
+ const [secret, setSecret] = useState('');
157
+ const [busy, setBusy] = useState(false);
158
+ const [error, setError] = useState<string | null>(null);
159
+ return (
160
+ <div className="flex flex-col gap-1.5">
161
+ <p className="text-detail text-ink-muted">
162
+ Register an OAuth app with the provider using this deployment&apos;s redirect URI
163
+ (<code>/api/secrets/oauth/callback</code>), then enter its client id and secret.
164
+ </p>
165
+ <div className="flex items-center gap-2">
166
+ <TextField value={clientId} onChange={(e) => setClientId(e.target.value)} placeholder="Client id" aria-label="Client id" className="w-44" />
167
+ <TextField type="password" value={secret} onChange={(e) => setSecret(e.target.value)} placeholder="Client secret" aria-label="Client secret" className="w-44" />
168
+ <Button
169
+ variant="primary"
170
+ size="sm"
171
+ disabled={busy || !clientId.trim() || !secret.trim()}
172
+ onClick={() => {
173
+ setBusy(true);
174
+ setError(null);
175
+ onSave(clientId.trim(), secret.trim())
176
+ .catch((err) => setError(err instanceof Error ? err.message : String(err)))
177
+ .finally(() => setBusy(false));
178
+ }}
179
+ >
180
+ Save
181
+ </Button>
182
+ <Button variant="quiet" size="sm" disabled={busy} onClick={onCancel}>
183
+ Cancel
184
+ </Button>
185
+ </div>
186
+ {error && <p className="text-detail text-danger">{error}</p>}
187
+ </div>
188
+ );
189
+ }
@@ -0,0 +1,212 @@
1
+ import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
2
+ import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';
3
+ import { MemoryRouter } from 'react-router-dom';
4
+ import type { ConnectPending, ConnectToolOAuth } from '../../services/connect.api';
5
+ import { AppRegistryContext, makeRegistry, type ConnectPanelProps } from '../../../../core/registry';
6
+ import { ConnectToolsPage } from '../ConnectToolsPage';
7
+ import { TOOL_CREDENTIALS_STALE_EVENT } from '../../../../core/events';
8
+
9
+ /**
10
+ * The managed-connector half of the Connect page, at the page boundary: the
11
+ * distribution's panel at the foot of the page and what it may ask of the
12
+ * page, and a Disconnect that goes to the row the connection lives on — the
13
+ * caller's for a personal sign-in, the shared one for a workspace connection.
14
+ */
15
+
16
+ const connectMock = vi.hoisted(() => ({
17
+ getConnectPending: vi.fn(),
18
+ startToolOAuth: vi.fn(),
19
+ getMcpOAuthRequest: vi.fn(),
20
+ completeMcpOAuth: vi.fn(),
21
+ }));
22
+ vi.mock('../../services/connect.api', () => connectMock);
23
+
24
+ const varsMock = vi.hoisted(() => ({
25
+ setUserVar: vi.fn(),
26
+ setAdminVar: vi.fn(),
27
+ deleteUserVar: vi.fn(),
28
+ deleteAdminVar: vi.fn(),
29
+ setOAuthClientSecret: vi.fn(),
30
+ checkToolConnection: vi.fn(),
31
+ }));
32
+ vi.mock('../../services/tool-secrets.api', () => varsMock);
33
+ vi.mock('../../services/secrets.api', () => ({ startOAuth: vi.fn() }));
34
+
35
+ /** A managed sign-in row as `/connect/pending` sends it. */
36
+ function managedRow(over: Partial<ConnectToolOAuth> = {}, card: Partial<NonNullable<ConnectToolOAuth['managed']>> = {}): ConnectToolOAuth {
37
+ return {
38
+ slug: 'microsoft365',
39
+ varName: 'ACCESS_TOKEN',
40
+ toolName: 'microsoft365',
41
+ key: 'microsoft365_ACCESS_TOKEN',
42
+ label: 'Microsoft 365 sign-in',
43
+ authorized: true,
44
+ needsReauth: false,
45
+ ownerConfigured: true,
46
+ ownerOnly: false,
47
+ canWrite: false,
48
+ managed: {
49
+ connectorId: 'microsoft365',
50
+ scopeSet: 'read',
51
+ tokenScope: 'user',
52
+ displayName: 'Microsoft 365',
53
+ icon: 'Mail',
54
+ description: 'Lets Hexis read your mail.',
55
+ permissions: ['Read your mail.'],
56
+ scopeSetLabel: 'Read',
57
+ dataResidency: 'EU',
58
+ subprocessor: 'Microsoft',
59
+ account: 'alice@acme.example',
60
+ ownApp: false,
61
+ available: true,
62
+ ...card,
63
+ },
64
+ ...over,
65
+ };
66
+ }
67
+
68
+ const workspaceRow = () =>
69
+ managedRow(
70
+ { slug: 'hubspot', varName: 'ACCESS_TOKEN', toolName: 'hubspot', key: 'hubspot_ACCESS_TOKEN', label: 'HubSpot sign-in', canWrite: true },
71
+ { connectorId: 'hubspot', tokenScope: 'shared', displayName: 'HubSpot', account: 'acme.hubspot.com' },
72
+ );
73
+
74
+ const listing = (...toolOAuth: ConnectToolOAuth[]): ConnectPending => ({ tools: [], oauth: [], toolOAuth });
75
+
76
+ const heard = vi.fn();
77
+
78
+ function renderPage(panel?: React.ComponentType<ConnectPanelProps>) {
79
+ const page = (
80
+ <MemoryRouter>
81
+ <ConnectToolsPage />
82
+ </MemoryRouter>
83
+ );
84
+ return render(panel ? <AppRegistryContext.Provider value={makeRegistry({ connectPanel: panel })}>{page}</AppRegistryContext.Provider> : page);
85
+ }
86
+
87
+ /** The connector's card, once the list that carries it has landed. */
88
+ const card = async (connectorId: string) => within(await screen.findByTestId(`connector-${connectorId}`));
89
+
90
+ beforeEach(() => {
91
+ window.history.replaceState(null, '', '/skills-and-tools/connect');
92
+ sessionStorage.clear();
93
+ heard.mockReset();
94
+ connectMock.getConnectPending.mockReset().mockResolvedValue(listing());
95
+ connectMock.getMcpOAuthRequest.mockReset();
96
+ varsMock.deleteUserVar.mockReset().mockResolvedValue(undefined);
97
+ varsMock.deleteAdminVar.mockReset().mockResolvedValue(undefined);
98
+ varsMock.checkToolConnection.mockReset();
99
+ window.addEventListener(TOOL_CREDENTIALS_STALE_EVENT, heard);
100
+ });
101
+ afterEach(() => window.removeEventListener(TOOL_CREDENTIALS_STALE_EVENT, heard));
102
+
103
+ describe('ConnectToolsPage: the distribution’s panel at the foot of the page', () => {
104
+ function Panel({ onChanged }: ConnectPanelProps) {
105
+ return <button onClick={onChanged}>Enable HubSpot</button>;
106
+ }
107
+
108
+ it('renders the registered panel once the list has loaded, and for a reader with nothing else to set up', async () => {
109
+ let answer!: (p: ConnectPending) => void;
110
+ connectMock.getConnectPending.mockReturnValue(new Promise<ConnectPending>((resolve) => (answer = resolve)));
111
+ renderPage(Panel);
112
+ // Not while the page still says "Loading…": the panel lands with the lists.
113
+ expect(screen.queryByRole('button', { name: 'Enable HubSpot' })).toBeNull();
114
+ answer(listing());
115
+ expect(await screen.findByRole('button', { name: 'Enable HubSpot' })).toBeInTheDocument();
116
+ });
117
+
118
+ it('renders no panel when none is registered', async () => {
119
+ renderPage();
120
+ await screen.findByRole('heading', { name: 'Connect your tools' });
121
+ await waitFor(() => expect(screen.queryByText('Loading…')).toBeNull());
122
+ expect(screen.queryByRole('button', { name: 'Enable HubSpot' })).toBeNull();
123
+ });
124
+
125
+ it('a change the panel reports is announced and the list fetched again, quietly', async () => {
126
+ renderPage(Panel);
127
+ const enable = await screen.findByRole('button', { name: 'Enable HubSpot' });
128
+ await waitFor(() => expect(connectMock.getConnectPending).toHaveBeenCalledTimes(1));
129
+ // The next listing (what the panel enabled) is held open, so the page's
130
+ // state WHILE it refetches is observable, not only the state after.
131
+ let answer!: (p: ConnectPending) => void;
132
+ connectMock.getConnectPending.mockReturnValue(new Promise<ConnectPending>((resolve) => (answer = resolve)));
133
+ fireEvent.click(enable);
134
+ await waitFor(() => expect(heard).toHaveBeenCalledTimes(1));
135
+ await waitFor(() => expect(connectMock.getConnectPending).toHaveBeenCalledTimes(2));
136
+ // Quietly: mid-refetch the page has not dropped to "Loading…", and the
137
+ // panel that asked is still mounted.
138
+ expect(screen.queryByText('Loading…')).toBeNull();
139
+ expect(screen.getByRole('button', { name: 'Enable HubSpot' })).toBeInTheDocument();
140
+ answer(listing(workspaceRow()));
141
+ expect(await screen.findByTestId('connector-hubspot')).toBeInTheDocument();
142
+ });
143
+ });
144
+
145
+ describe('ConnectToolsPage: skipping a managed connector, as any sign-in row can be skipped', () => {
146
+ it('a personal sign-in skipped has its token removed like a row’s, reads Skipped, and comes back with Include', async () => {
147
+ connectMock.getConnectPending.mockResolvedValue(listing(managedRow({ authorized: true })));
148
+ renderPage();
149
+ fireEvent.click((await card('microsoft365')).getByRole('checkbox', { name: /Skip this tool/ }));
150
+ await waitFor(() => expect(varsMock.deleteUserVar).toHaveBeenCalledWith('microsoft365', 'ACCESS_TOKEN'));
151
+ expect(varsMock.deleteAdminVar).not.toHaveBeenCalled();
152
+ expect(await (await card('microsoft365')).findByText('Skipped')).toBeInTheDocument();
153
+ fireEvent.click((await card('microsoft365')).getByRole('button', { name: 'Include' }));
154
+ await waitFor(() => expect(screen.getByTestId('connector-microsoft365')).not.toHaveTextContent('Skipped'));
155
+ });
156
+
157
+ it('a workspace connection offers no skip: it is everyone’s, and nothing could take it out of one agent’s connection', async () => {
158
+ connectMock.getConnectPending.mockResolvedValue(listing(workspaceRow()));
159
+ renderPage();
160
+ const hubspot = await card('hubspot');
161
+ expect(hubspot.queryByRole('checkbox')).toBeNull();
162
+ expect(hubspot.queryByText('Skipped')).toBeNull();
163
+ expect(varsMock.deleteAdminVar).not.toHaveBeenCalled();
164
+ expect(varsMock.deleteUserVar).not.toHaveBeenCalled();
165
+ });
166
+ });
167
+
168
+ describe('ConnectToolsPage: disconnecting a managed sign-in', () => {
169
+ it('a personal sign-in is removed from the caller’s row, announced, and the list fetched again', async () => {
170
+ let answer!: (p: ConnectPending) => void;
171
+ connectMock.getConnectPending
172
+ .mockResolvedValueOnce(listing(managedRow()))
173
+ .mockReturnValue(new Promise<ConnectPending>((resolve) => (answer = resolve)));
174
+ renderPage();
175
+ fireEvent.click((await card('microsoft365')).getByRole('button', { name: 'Disconnect' }));
176
+ await waitFor(() => expect(varsMock.deleteUserVar).toHaveBeenCalledWith('microsoft365', 'ACCESS_TOKEN'));
177
+ expect(varsMock.deleteAdminVar).not.toHaveBeenCalled();
178
+ await waitFor(() => expect(heard).toHaveBeenCalledTimes(1));
179
+ await waitFor(() => expect(connectMock.getConnectPending).toHaveBeenCalledTimes(2));
180
+ // Quietly: mid-refetch the card is still on the page and nothing says "Loading…".
181
+ expect(screen.queryByText('Loading…')).toBeNull();
182
+ expect(screen.getByTestId('connector-microsoft365')).toBeInTheDocument();
183
+ answer(listing(managedRow({ authorized: false }, { account: null })));
184
+ // The refetched row: nothing stored any more.
185
+ expect(await (await card('microsoft365')).findByText('Ready to connect')).toBeInTheDocument();
186
+ });
187
+
188
+ it('a workspace connection is removed from the shared row, by a writer, and the list fetched again', async () => {
189
+ connectMock.getConnectPending
190
+ .mockResolvedValueOnce(listing(workspaceRow()))
191
+ .mockResolvedValue(listing({ ...workspaceRow(), authorized: false, managed: { ...workspaceRow().managed!, account: null } }));
192
+ renderPage();
193
+ fireEvent.click((await card('hubspot')).getByRole('button', { name: 'Disconnect' }));
194
+ await waitFor(() => expect(varsMock.deleteAdminVar).toHaveBeenCalledWith('hubspot', 'ACCESS_TOKEN'));
195
+ expect(varsMock.deleteUserVar).not.toHaveBeenCalled();
196
+ await waitFor(() => expect(heard).toHaveBeenCalledTimes(1));
197
+ await waitFor(() => expect(connectMock.getConnectPending).toHaveBeenCalledTimes(2));
198
+ expect(await (await card('hubspot')).findByText('Ready to connect')).toBeInTheDocument();
199
+ });
200
+
201
+ it('a disconnect the server refuses is shown, announces nothing, and leaves the card usable', async () => {
202
+ connectMock.getConnectPending.mockResolvedValue(listing(managedRow()));
203
+ varsMock.deleteUserVar.mockRejectedValue(new Error('Nope.'));
204
+ renderPage();
205
+ const disconnect = (await card('microsoft365')).getByRole('button', { name: 'Disconnect' });
206
+ fireEvent.click(disconnect);
207
+ expect(await screen.findByText('Nope.')).toBeInTheDocument();
208
+ expect(heard).not.toHaveBeenCalled();
209
+ expect(connectMock.getConnectPending).toHaveBeenCalledTimes(1);
210
+ await waitFor(() => expect(disconnect).toBeEnabled());
211
+ });
212
+ });
@@ -0,0 +1,182 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
3
+ import { MemoryRouter } from 'react-router-dom';
4
+ import { ManagedConnectorCard } from '../ManagedConnectorCard';
5
+ import { managedCardState, type ManagedToolOAuth } from '../../utils/managed-card-state';
6
+
7
+ /** A managed sign-in row as `/connect/pending` sends it, with the parts under test overridden. */
8
+ function row(over: Partial<ManagedToolOAuth> = {}, managedOver: Partial<ManagedToolOAuth['managed']> = {}): ManagedToolOAuth {
9
+ return {
10
+ slug: 'microsoft365',
11
+ varName: 'ACCESS_TOKEN',
12
+ toolName: 'microsoft365',
13
+ key: 'microsoft365_ACCESS_TOKEN',
14
+ label: 'Microsoft 365 sign-in',
15
+ authorized: false,
16
+ needsReauth: false,
17
+ ownerConfigured: true,
18
+ ownerOnly: false,
19
+ canWrite: false,
20
+ managed: {
21
+ connectorId: 'microsoft365',
22
+ scopeSet: 'read',
23
+ tokenScope: 'user',
24
+ displayName: 'Microsoft 365',
25
+ icon: 'Mail',
26
+ description: 'Lets Hexis read your mail.',
27
+ permissions: ['Read your mail.'],
28
+ scopeSetLabel: 'Read',
29
+ dataResidency: 'EU',
30
+ subprocessor: 'Microsoft',
31
+ account: null,
32
+ ownApp: false,
33
+ available: true,
34
+ ...managedOver,
35
+ },
36
+ ...over,
37
+ };
38
+ }
39
+
40
+ describe('the state a managed connector card shows', () => {
41
+ it.each([
42
+ ['ready', row()],
43
+ ['connected', row({ authorized: true })],
44
+ ['needs-reconnect', row({ authorized: true, needsReauth: true })],
45
+ ['unavailable', row({}, { available: false })],
46
+ // A stored token still works while the broker is unreachable: the card
47
+ // says so, and withholds the buttons that would need the broker.
48
+ ['connected', row({ authorized: true }, { available: false })],
49
+ ['owner-only', row({ ownerOnly: true })],
50
+ // What is stored comes before who may change it: a workspace connection
51
+ // an owner made is connected for its readers too, and one that fell
52
+ // under-scoped needs a reconnect whoever has to make it.
53
+ ['connected', row({ authorized: true, ownerOnly: true }, { tokenScope: 'shared' })],
54
+ ['needs-reconnect', row({ authorized: true, needsReauth: true, ownerOnly: true }, { tokenScope: 'shared' })],
55
+ // An owner's own app makes the deployment's own flow apply: no broker needed.
56
+ ['ready', row({}, { available: false, ownApp: true })],
57
+ ] as const)('%s', (expected, o) => {
58
+ expect(managedCardState(o)).toBe(expected);
59
+ });
60
+ });
61
+
62
+ describe('ManagedConnectorCard', () => {
63
+ const renderCard = (
64
+ o: ManagedToolOAuth,
65
+ handlers: Partial<{ onConnect: () => void; onDisconnect: () => void; onOwnApp: (id: string, secret: string) => Promise<void> }> = {},
66
+ ) =>
67
+ render(
68
+ <MemoryRouter>
69
+ <ManagedConnectorCard
70
+ o={o}
71
+ busy={false}
72
+ onConnect={handlers.onConnect ?? vi.fn()}
73
+ onDisconnect={handlers.onDisconnect ?? vi.fn()}
74
+ onOwnApp={handlers.onOwnApp}
75
+ />
76
+ </MemoryRouter>,
77
+ );
78
+
79
+ it('offers Connect when nothing is stored, and says what the connector may do', () => {
80
+ const onConnect = vi.fn();
81
+ renderCard(row(), { onConnect });
82
+ expect(screen.getByText('Ready to connect')).toBeInTheDocument();
83
+ expect(screen.getByText('Read your mail.')).toBeInTheDocument();
84
+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));
85
+ expect(onConnect).toHaveBeenCalledTimes(1);
86
+ expect(screen.queryByRole('button', { name: 'Disconnect' })).toBeNull();
87
+ });
88
+
89
+ it('shows who is signed in, with Reconnect and Disconnect', () => {
90
+ const onDisconnect = vi.fn();
91
+ renderCard(row({ authorized: true }, { account: 'alice@acme.example' }), { onDisconnect });
92
+ // "Signed in", never "Connected": the page says Connected only after a real call.
93
+ expect(screen.getByText('Signed in as alice@acme.example')).toBeInTheDocument();
94
+ expect(screen.queryByText(/Connected/)).toBeNull();
95
+ fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }));
96
+ expect(onDisconnect).toHaveBeenCalledTimes(1);
97
+ expect(screen.getByRole('button', { name: 'Reconnect' })).toBeInTheDocument();
98
+ });
99
+
100
+ it('says Needs reconnect when the token no longer covers the tool', () => {
101
+ renderCard(row({ authorized: true, needsReauth: true }));
102
+ expect(screen.getByText('Needs reconnect')).toBeInTheDocument();
103
+ expect(screen.getByRole('button', { name: 'Reconnect' })).toBeInTheDocument();
104
+ });
105
+
106
+ it('offers nothing to press while the deployment has no broker, and names the admin’s job', () => {
107
+ renderCard(row({}, { available: false }));
108
+ expect(screen.getByText('Not available yet')).toBeInTheDocument();
109
+ expect(screen.queryByRole('button', { name: /Connect/ })).toBeNull();
110
+ expect(screen.getByText(/not connected to a connector broker yet/)).toBeInTheDocument();
111
+ });
112
+
113
+ it('keeps a stored token usable while the broker is unreachable: Disconnect stays, Reconnect goes', () => {
114
+ renderCard(row({ authorized: true }, { available: false, account: 'alice@acme.example' }));
115
+ expect(screen.getByText('Signed in as alice@acme.example')).toBeInTheDocument();
116
+ expect(screen.getByRole('button', { name: 'Disconnect' })).toBeInTheDocument();
117
+ expect(screen.queryByRole('button', { name: /Reconnect|Connect/ })).toBeNull();
118
+ });
119
+
120
+ it('a workspace connection a reader cannot make is greyed as needing an owner', () => {
121
+ renderCard(row({ ownerOnly: true }, { tokenScope: 'shared' }));
122
+ expect(screen.getByText('Needs an owner')).toBeInTheDocument();
123
+ expect(screen.getByText(/One connection for the whole workspace/)).toBeInTheDocument();
124
+ expect(screen.queryByRole('button', { name: /Connect/ })).toBeNull();
125
+ });
126
+
127
+ it('a workspace connection an owner made reads as signed in to a reader, who gets no control over it', () => {
128
+ renderCard(row({ authorized: true, ownerOnly: true }, { tokenScope: 'shared', account: 'acme.hubspot.com' }));
129
+ expect(screen.getByText('Signed in as acme.hubspot.com')).toBeInTheDocument();
130
+ expect(screen.queryByText('Needs an owner')).toBeNull();
131
+ expect(screen.queryByRole('button', { name: /^(?:Connect|Reconnect|Disconnect)$/ })).toBeNull();
132
+ });
133
+
134
+ it('an owner can bring the deployment’s own app: the form sends the client id and the secret', async () => {
135
+ const onOwnApp = vi.fn(async () => undefined);
136
+ renderCard(row({ canWrite: true }), { onOwnApp });
137
+ fireEvent.click(screen.getByRole('button', { name: 'Use our own app instead' }));
138
+ fireEvent.change(screen.getByLabelText('Client id'), { target: { value: 'own-client' } });
139
+ fireEvent.change(screen.getByLabelText('Client secret'), { target: { value: 'own-secret' } });
140
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
141
+ await waitFor(() => expect(onOwnApp).toHaveBeenCalledWith('own-client', 'own-secret'));
142
+ // The form closes once the save settled.
143
+ await waitFor(() => expect(screen.queryByLabelText('Client id')).toBeNull());
144
+ });
145
+
146
+ it('a workspace connection with an own app pinned says so, not that a broker is missing', () => {
147
+ renderCard(row({ canWrite: true }, { tokenScope: 'shared', ownApp: true, available: true }));
148
+ expect(screen.getByText(/own app pinned, which it cannot use/)).toBeInTheDocument();
149
+ expect(screen.queryByText(/not connected to a connector broker/)).toBeNull();
150
+ expect(screen.queryByRole('button', { name: /^(?:Connect|Reconnect)$/ })).toBeNull();
151
+ });
152
+
153
+ describe('include/skip, as every sign-in row carries it', () => {
154
+ it('shows the toggle only when the page offers one, and reports a click', () => {
155
+ renderCard(row());
156
+ expect(screen.queryByRole('checkbox')).toBeNull();
157
+ cleanup();
158
+ const onToggle = vi.fn();
159
+ render(
160
+ <MemoryRouter>
161
+ <ManagedConnectorCard o={row({ authorized: true })} busy={false} onConnect={vi.fn()} onDisconnect={vi.fn()} on onToggle={onToggle} />
162
+ </MemoryRouter>,
163
+ );
164
+ fireEvent.click(screen.getByRole('checkbox', { name: /Skip this tool/ }));
165
+ expect(onToggle).toHaveBeenCalledTimes(1);
166
+ expect(screen.getByRole('button', { name: 'Reconnect' })).toBeInTheDocument();
167
+ });
168
+
169
+ it('a skipped card is greyed, says so, and offers Include and nothing else', () => {
170
+ const onToggle = vi.fn();
171
+ render(
172
+ <MemoryRouter>
173
+ <ManagedConnectorCard o={row({ authorized: true })} busy={false} onConnect={vi.fn()} onDisconnect={vi.fn()} on={false} onToggle={onToggle} />
174
+ </MemoryRouter>,
175
+ );
176
+ expect(screen.getByText('Skipped')).toBeInTheDocument();
177
+ expect(screen.queryByRole('button', { name: /^(?:Connect|Reconnect|Disconnect)$/ })).toBeNull();
178
+ fireEvent.click(screen.getByRole('button', { name: 'Include' }));
179
+ expect(onToggle).toHaveBeenCalledTimes(1);
180
+ });
181
+ });
182
+ });
@@ -109,6 +109,7 @@ describe('SecretsPage', () => {
109
109
  label: null,
110
110
  key: 'heyreach_API_KEY',
111
111
  adminConfigured: true,
112
+ adminKind: 'static',
112
113
  userConfigured: false,
113
114
  },
114
115
  ],
@@ -179,6 +180,7 @@ describe('SecretsPage', () => {
179
180
  label: null,
180
181
  key: 'heyreach_API_KEY',
181
182
  adminConfigured: true,
183
+ adminKind: 'static',
182
184
  userConfigured: false,
183
185
  },
184
186
  ],
@@ -338,6 +340,7 @@ describe('SecretsPage', () => {
338
340
  label: null,
339
341
  key: 'heyreach_API_KEY',
340
342
  adminConfigured: true,
343
+ adminKind: 'static',
341
344
  userConfigured: false,
342
345
  },
343
346
  ],
@@ -48,6 +48,7 @@ const tool = (slug: string): ToolSecrets => ({
48
48
  label: null,
49
49
  key: `${slug}_API_KEY`,
50
50
  adminConfigured: true,
51
+ adminKind: 'static',
51
52
  userConfigured: false,
52
53
  },
53
54
  ],
@@ -48,6 +48,7 @@ function v(over: Partial<ToolVarStatus> & { name: string }): ToolVarStatus {
48
48
  label: null,
49
49
  key: `k_${over.name}`,
50
50
  adminConfigured: false,
51
+ adminKind: null,
51
52
  userConfigured: false,
52
53
  ...over,
53
54
  };
@@ -11,3 +11,5 @@ export { useSavedKeyProbe } from './probe/useSavedKeyProbe';
11
11
  export { startToolOAuth } from './services/connect.api';
12
12
  export { deleteAdminVar, listToolSecrets, setAdminVar, setOAuthClientSecret, setUserVar } from './services/tool-secrets.api';
13
13
  export type { ProbeVerdict, ToolSecrets, ToolVarStatus } from './services/tool-secrets.api';
14
+ /** Whether a managed sign-in can be started from here: the one rule the Connect page and the tool page share. */
15
+ export { canStartSignIn } from './utils/managed-card-state';
@@ -104,6 +104,7 @@ describe('the tool page and the rows agree, verdict for verdict', () => {
104
104
  label: null,
105
105
  key: 'github_API_KEY',
106
106
  adminConfigured: true,
107
+ adminKind: 'static',
107
108
  userConfigured: true,
108
109
  },
109
110
  ],