@bevel-software/platform-core-frontend 0.21.0 → 0.22.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 (34) hide show
  1. package/package.json +2 -2
  2. package/src/core/registry.ts +57 -0
  3. package/src/modules/access/__tests__/ManageAccessDialog.request.test.tsx +376 -0
  4. package/src/modules/access/components/AccessRequestControl.tsx +155 -0
  5. package/src/modules/{library → access}/components/AccessRequestsBanner.tsx +62 -24
  6. package/src/modules/access/components/ManageAccessDialog.tsx +81 -4
  7. package/src/modules/access/hooks/useAccessRequests.ts +183 -0
  8. package/src/modules/access/requests.api.ts +121 -0
  9. package/src/modules/auth/components/LoginScreen.tsx +5 -0
  10. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +171 -38
  11. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +34 -19
  12. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +173 -6
  13. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +155 -98
  14. package/src/modules/library/__tests__/SkillPage.test.tsx +15 -0
  15. package/src/modules/library/__tests__/ToolPage.test.tsx +15 -1
  16. package/src/modules/library/__tests__/title-row-actions.ts +53 -1
  17. package/src/modules/library/components/PluginJoinRequests.tsx +2 -2
  18. package/src/modules/library/components/skill-page/SkillPage.tsx +2 -2
  19. package/src/modules/library/components/tool-page/ToolPage.tsx +11 -1
  20. package/src/modules/library/hooks/useJoinRequests.ts +26 -101
  21. package/src/modules/pr/services/pr-merge.api.ts +10 -2
  22. package/src/modules/settings/components/DeploymentPage.tsx +22 -0
  23. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +72 -4
  24. package/src/modules/setup/__tests__/setup.first-run.test.tsx +276 -0
  25. package/src/modules/setup/__tests__/setup.github.test.tsx +416 -0
  26. package/src/modules/setup/__tests__/setup.kept-draft.test.tsx +275 -0
  27. package/src/modules/setup/__tests__/setup.repository.test.tsx +373 -0
  28. package/src/modules/setup/__tests__/setup.test.tsx +8 -14
  29. package/src/modules/setup/components/GitHubRepositoryPanel.tsx +369 -0
  30. package/src/modules/setup/components/SetupGate.tsx +1 -0
  31. package/src/modules/setup/components/SetupScreen.tsx +464 -38
  32. package/src/modules/setup/services/setup.api.ts +93 -0
  33. package/src/modules/setup/utils/kept-draft.ts +86 -0
  34. package/src/shared/components/SlotBoundary.tsx +51 -0
@@ -1,7 +1,8 @@
1
- import { useCallback, useEffect, useState } from 'react';
2
- import { DEFAULT_BRANCH } from '@bevel-software/platform-shared';
3
- import { grantAccess } from '../../access/api';
4
- import { cancelPullRequest } from '../../pr/services/pr-cancel.api';
1
+ import { useMemo } from 'react';
2
+ import {
3
+ useAccessRequests,
4
+ type AccessRequestsState,
5
+ } from '../../access/hooks/useAccessRequests';
5
6
  import {
6
7
  listJoinRequests,
7
8
  reconcileJoinRequest,
@@ -11,31 +12,18 @@ import {
11
12
  import { useLibraryToast } from '../state/toast.context';
12
13
 
13
14
  /**
14
- * The join requests one plugin's managers can answer, and the two ways to
15
- * answer them.
16
- *
17
- * ACCEPTING IS A GRANT, NOT A MERGE. A proposal is "give this principal this
18
- * verb on the plugin folder", so accepting it calls the ordinary access-grant
19
- * API — the same endpoint the Manage-access dialog uses, with the same gate,
20
- * lock and commit. The request's branch is never merged, so nothing else it
21
- * carries can ride in on an approval, and a request naming five people can be
22
- * answered with two yeses and three ignores.
23
- *
24
- * The request then retires ITSELF: it is open exactly while its `access.md`
25
- * grants something the default branch does not, so once the accepted grant
26
- * lands the diff is empty and the server closes it and deletes the branch.
27
- * `reconcile` just asks for that check immediately instead of waiting for the
28
- * next listing (which does it too).
15
+ * The Library's face of {@link useAccessRequests}: one plugin's (or skill's)
16
+ * join requests, with the failures said as Library toasts.
29
17
  *
30
- * Fetching is unconditional and degrades to `[]` — the endpoint answers `[]`
31
- * to non-managers rather than 403, so "am I a manager here" stays a question
32
- * only the server answers.
18
+ * Everything about how a request is answered lives in the access module now —
19
+ * accepting is a grant, declining rejects the change request, and the request
20
+ * retires itself. What stays here is where the words go: the Library has a
21
+ * toast host, and the Manage access dialog does not, which is why the generic
22
+ * hook reports failures as state and lets each surface choose.
33
23
  */
34
24
  export interface JoinRequestsState {
35
25
  requests: JoinRequest[];
36
- /** Grant one proposal, then settle the request if that was the last one. */
37
26
  accept(request: JoinRequest, proposal: JoinProposal): Promise<void>;
38
- /** Decline the whole request — reject the change request. */
39
27
  decline(request: JoinRequest): Promise<void>;
40
28
  reload(): void;
41
29
  }
@@ -62,83 +50,20 @@ export function useJoinRequests(
62
50
  folder: string | null,
63
51
  api: JoinRequestsApi = PLUGIN_JOIN_API,
64
52
  ): JoinRequestsState {
65
- // Keyed by the plugin they came from: a page that moves from skill A to
66
- // skill B without unmounting must not show A's requests until B's arrive —
67
- // a banner that lets an editor grant A's proposal against B's folder.
68
- const [loaded, setLoaded] = useState<{ plugin: string; rows: JoinRequest[] } | null>(null);
69
- const requests = loaded?.plugin === plugin ? loaded.rows : [];
70
- const [revision, setRevision] = useState(0);
71
53
  const toast = useLibraryToast();
72
-
73
- useEffect(() => {
74
- let cancelled = false;
75
- api.list(plugin)
76
- .then((rows) => {
77
- if (!cancelled) setLoaded({ plugin, rows });
78
- })
79
- .catch(() => {
80
- // Silent: a manager surface that fails must not put an error banner in
81
- // front of somebody who came to read a skill.
82
- });
83
- return () => {
84
- cancelled = true;
85
- };
86
- }, [plugin, revision, api]);
87
-
88
- const reload = useCallback(() => setRevision((r) => r + 1), []);
89
-
90
- const accept = useCallback(
91
- async (request: JoinRequest, proposal: JoinProposal) => {
92
- if (!folder) return;
93
- try {
94
- await grantAccess(encodeURIComponent(DEFAULT_BRANCH), {
95
- path: folder,
96
- kind: 'folder',
97
- verb: proposal.verb,
98
- principal: proposal.principal,
99
- });
100
- } catch (err) {
101
- toast(err instanceof Error ? err.message : "Couldn't grant that: try again.", 'danger');
102
- setRevision((r) => r + 1);
103
- return;
104
- }
105
- // Drop the accepted proposal locally so the row goes immediately; the
106
- // refetch below is what makes it true.
107
- setLoaded((cur) =>
108
- cur && cur.plugin === plugin
109
- ? {
110
- ...cur,
111
- rows: cur.rows.map((r) =>
112
- r.number === request.number
113
- ? {
114
- ...r,
115
- proposals: r.proposals.filter(
116
- (p) => !(p.id === proposal.id && p.verb === proposal.verb),
117
- ),
118
- }
119
- : r,
120
- ),
121
- }
122
- : cur,
123
- );
124
- toast(`${proposal.label} now has ${proposal.verb} access.`);
125
- await api.reconcile(plugin, request.number).catch(() => false);
126
- setRevision((r) => r + 1);
127
- },
128
- [folder, plugin, toast, api],
129
- );
130
-
131
- const decline = useCallback(
132
- async (request: JoinRequest) => {
133
- try {
134
- await cancelPullRequest(request.number);
135
- } catch {
136
- toast("Couldn't dismiss that: try again.", 'danger');
137
- }
138
- setRevision((r) => r + 1);
139
- },
140
- [toast],
54
+ const source = useMemo(
55
+ () => ({
56
+ list: () => api.list(plugin),
57
+ reconcile: (number: number) => api.reconcile(plugin, number),
58
+ }),
59
+ [api, plugin],
141
60
  );
142
-
143
- return { requests, accept, decline, reload };
61
+ const state: AccessRequestsState = useAccessRequests({
62
+ itemKey: plugin,
63
+ source,
64
+ grantOn: folder ? { path: folder, kind: 'folder' } : null,
65
+ onError: (message) => toast(message, 'danger'),
66
+ onAccepted: (message) => toast(message),
67
+ });
68
+ return state;
144
69
  }
@@ -1,3 +1,4 @@
1
+ import type { ChangeRequestUpdateResult } from '@bevel-software/platform-shared';
1
2
  import { authFetch } from '../../../lib/api';
2
3
  import { handleApiResponse } from '../../git/services/git.api';
3
4
 
@@ -42,9 +43,16 @@ export async function mergePullRequest(
42
43
  * `change-request-conflicts` error payload (status 409) listing the
43
44
  * conflicting paths — the caller catches it via `GitApiError` and
44
45
  * routes the agent into the resolution flow.
46
+ *
47
+ * Answers the refreshed detail itself, plus `updatedPaths` — which files the
48
+ * merge changed on the branch. A caller that is already showing the request's
49
+ * files replaces exactly those, and needs no further detail read: this one was
50
+ * assembled after the merge, with the carried approvals in it.
45
51
  */
46
- export async function refreshChangeRequestFromTarget(prNumber: number): Promise<unknown> {
47
- return handleApiResponse(
52
+ export async function refreshChangeRequestFromTarget(
53
+ prNumber: number,
54
+ ): Promise<ChangeRequestUpdateResult> {
55
+ return handleApiResponse<ChangeRequestUpdateResult>(
48
56
  await authFetch(`/api/workflow/change-requests/${prNumber}/update-from-target`, {
49
57
  method: 'POST',
50
58
  headers: { 'Content-Type': 'application/json' },
@@ -1,8 +1,10 @@
1
1
  import { PageShell } from '../../../shared/components/PageShell';
2
2
  import { Banner, Button } from '../../../shared/components';
3
+ import { SlotBoundary } from '../../../shared/components/SlotBoundary';
3
4
  import { useAdmin } from '../../admin/state/admin.context';
4
5
  import { useSetupStatus } from '../../setup/hooks/useSetupStatus';
5
6
  import { SetupScreen } from '../../setup/components/SetupScreen';
7
+ import { useAppRegistry } from '../../../core/registry';
6
8
 
7
9
  /**
8
10
  * Deployment settings, routed at `/deployment` — the first-run setup screen
@@ -27,6 +29,8 @@ import { SetupScreen } from '../../setup/components/SetupScreen';
27
29
  */
28
30
  export function DeploymentPage() {
29
31
  const { isAdmin } = useAdmin();
32
+ // What the distribution adds to this page, if anything — see the slot.
33
+ const { deploymentPanel: DeploymentPanel } = useAppRegistry();
30
34
  // Read the shared way (`useSetupStatus`: latest read wins, a failed read
31
35
  // keeps the last status). Non-admins never read: the endpoint would answer
32
36
  // them safely (status without settings), but this page has already told them
@@ -73,12 +77,30 @@ export function DeploymentPage() {
73
77
  settings={status.settings}
74
78
  sync={status.sync}
75
79
  oidcVerification={status.oidcVerification}
80
+ repository={status.repository}
76
81
  kbInit={status.kbInit}
77
82
  onSaved={refresh}
78
83
  variant="settings"
79
84
  />
80
85
  </div>
81
86
  )}
87
+
88
+ {/* The distribution's panel, last on the page and outside every
89
+ condition above: it does not depend on the settings, so neither a
90
+ load in flight nor a failed one takes it away.
91
+
92
+ And the other way round: the panel is code core did not write, so
93
+ it renders inside a boundary. A throw in it costs its own place on
94
+ the page and not the form above — the form is where an admin fixes
95
+ the sign-in or the repository connection, and must not go down with
96
+ a panel it has nothing to do with. */}
97
+ {DeploymentPanel && (
98
+ <div className="mt-10" data-testid="deployment-panel">
99
+ <SlotBoundary label="workspace panel">
100
+ <DeploymentPanel />
101
+ </SlotBoundary>
102
+ </div>
103
+ )}
82
104
  </PageShell>
83
105
  );
84
106
  }
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
2
  import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
3
3
  import { AdminContext, type AdminContextValue } from '../../../admin/state/admin.context';
4
4
  import { KbInitFailed } from '../../../setup/services/setup.api';
5
+ import { AppRegistryContext, EMPTY_REGISTRY, type AppRegistry } from '../../../../core/registry';
5
6
 
6
7
  /**
7
8
  * The deployment settings page — first-run setup with a permanent address.
@@ -50,14 +51,22 @@ const COMPLETE_STATUS = {
50
51
  ],
51
52
  };
52
53
 
53
- function renderPage(value: AdminContextValue) {
54
+ function renderPage(value: AdminContextValue, registry: AppRegistry = EMPTY_REGISTRY) {
54
55
  return render(
55
- <AdminContext.Provider value={value}>
56
- <DeploymentPage />
57
- </AdminContext.Provider>,
56
+ <AppRegistryContext.Provider value={registry}>
57
+ <AdminContext.Provider value={value}>
58
+ <DeploymentPage />
59
+ </AdminContext.Provider>
60
+ </AppRegistryContext.Provider>,
58
61
  );
59
62
  }
60
63
 
64
+ /** What a distribution would put at the foot of the page. */
65
+ function WorkspacePanel() {
66
+ return <section aria-label="Workspace">Delete this workspace</section>;
67
+ }
68
+ const WITH_PANEL: AppRegistry = { ...EMPTY_REGISTRY, deploymentPanel: WorkspacePanel };
69
+
61
70
  describe('DeploymentPage', () => {
62
71
  beforeEach(() => {
63
72
  apiMock.fetchSetupStatus.mockReset();
@@ -110,6 +119,65 @@ describe('DeploymentPage', () => {
110
119
  expect(facadeMock.fetchGitHubFacade).not.toHaveBeenCalled();
111
120
  });
112
121
 
122
+ /**
123
+ * The distribution's slot: what a deployment is beyond its settings (a
124
+ * hosted workspace's plan, its deletion) is not core's to know, so the page
125
+ * gives it a place and nothing more.
126
+ */
127
+ it('renders the distribution panel last on the page, after the form and its save button', async () => {
128
+ renderPage(admin(true), WITH_PANEL);
129
+ const panel = await screen.findByRole('region', { name: 'Workspace' });
130
+ const save = await screen.findByRole('button', { name: 'Save and continue' });
131
+ expect(save.compareDocumentPosition(panel) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
132
+ expect(screen.getByTestId('deployment-panel')).toContainElement(panel);
133
+ });
134
+
135
+ it('keeps the distribution panel when the settings cannot be loaded', async () => {
136
+ apiMock.fetchSetupStatus.mockRejectedValueOnce(new Error('down'));
137
+ renderPage(admin(true), WITH_PANEL);
138
+ expect(await screen.findByText(/Couldn't load the deployment settings/)).toBeInTheDocument();
139
+ // A way out of the deployment must not depend on its settings being readable.
140
+ expect(screen.getByRole('region', { name: 'Workspace' })).toBeInTheDocument();
141
+ });
142
+
143
+ it('shows the distribution panel to admins only, and nothing in its place without one', async () => {
144
+ renderPage(admin(false), WITH_PANEL);
145
+ expect(screen.getByText(/Admins only/)).toBeInTheDocument();
146
+ expect(screen.queryByRole('region', { name: 'Workspace' })).toBeNull();
147
+ expect(screen.queryByTestId('deployment-panel')).toBeNull();
148
+ });
149
+
150
+ it('ends with the form when no distribution panel is registered', async () => {
151
+ renderPage(admin(true));
152
+ await screen.findByText('Provider address');
153
+ expect(screen.queryByTestId('deployment-panel')).toBeNull();
154
+ });
155
+
156
+ /**
157
+ * The other direction of the same independence: the panel is code core did
158
+ * not write, and a throw in it must cost the panel's own place, not the
159
+ * form an admin came here to use.
160
+ */
161
+ it('keeps the settings form when the distribution panel throws, and says so in its place', async () => {
162
+ function BrokenPanel(): never {
163
+ throw new Error('the distribution has a bug');
164
+ }
165
+ // React reports a caught render error on the console, and so does the
166
+ // boundary; both are expected here and neither belongs in the run's output.
167
+ const quiet = vi.spyOn(console, 'error').mockImplementation(() => undefined);
168
+ try {
169
+ renderPage(admin(true), { ...EMPTY_REGISTRY, deploymentPanel: BrokenPanel });
170
+ expect(await screen.findByText('Provider address')).toBeInTheDocument();
171
+ expect(screen.getByRole('button', { name: 'Save and continue' })).toBeInTheDocument();
172
+ const slot = screen.getByTestId('deployment-panel');
173
+ expect(slot).toHaveTextContent(/workspace panel couldn.t be shown/);
174
+ expect(slot).toHaveTextContent(/rest of this page is unaffected/);
175
+ expect(quiet).toHaveBeenCalled();
176
+ } finally {
177
+ quiet.mockRestore();
178
+ }
179
+ });
180
+
113
181
  it('tells a non-admin this is not theirs, and never fetches the settings', () => {
114
182
  renderPage(admin(false));
115
183
  expect(screen.getByText(/Admins only/)).toBeInTheDocument();
@@ -0,0 +1,276 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { fireEvent, render, screen, within } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+
5
+ const api = vi.hoisted(() => ({
6
+ fetchSetupStatus: vi.fn(),
7
+ saveSettings: vi.fn(),
8
+ testConnection: vi.fn(),
9
+ testOidc: vi.fn(),
10
+ syncNow: vi.fn(),
11
+ }));
12
+ vi.mock('../services/setup.api', async () => {
13
+ const actual = await vi.importActual<typeof import('../services/setup.api')>('../services/setup.api');
14
+ return { ...actual, ...api };
15
+ });
16
+ vi.mock('../../settings/services/github-facade.api', () => ({
17
+ fetchGitHubFacade: vi.fn(),
18
+ rotateGitHubFacade: vi.fn(),
19
+ fetchMarketplaceRegistration: vi.fn(async () => false),
20
+ setMarketplaceRegistration: vi.fn(),
21
+ }));
22
+
23
+ import { AppRegistryContext, makeRegistry, type AppRegistry, type SignInOptionPanelProps } from '../../../core/registry';
24
+ import { SetupScreen } from '../components/SetupScreen';
25
+ import { SettingsProblems, type SettingStatus } from '../services/setup.api';
26
+
27
+ const setting = (key: string, section: SettingStatus['section'], extra: Partial<SettingStatus> = {}): SettingStatus => ({
28
+ key,
29
+ section,
30
+ source: 'unset',
31
+ value: '',
32
+ configured: false,
33
+ secret: false,
34
+ restartToApply: false,
35
+ ...extra,
36
+ });
37
+
38
+ const settingsWith = (configured: boolean): SettingStatus[] => [
39
+ setting('kbRepoUrl', 'knowledge-base'),
40
+ setting('gitToken', 'knowledge-base', { secret: true, value: undefined }),
41
+ setting('oidcIssuerUrl', 'sign-in', { configured, value: configured ? 'https://login.example.com' : '' }),
42
+ setting('oidcClientId', 'sign-in', { configured, value: configured ? 'app' : '' }),
43
+ setting('oidcClientSecret', 'sign-in', { configured, secret: true, value: undefined }),
44
+ setting('allowedEmailDomains', 'sign-in'),
45
+ setting('auditRetentionDays', 'audit'),
46
+ ];
47
+
48
+ function ManagedPanel({ variant, ownProviderConfigured }: SignInOptionPanelProps) {
49
+ return (
50
+ <p data-testid="managed-panel">
51
+ managed sign-in on {variant}, own provider {ownProviderConfigured ? 'configured' : 'absent'}
52
+ </p>
53
+ );
54
+ }
55
+
56
+ const hosted = makeRegistry({ signInOption: { label: 'Google and Microsoft', Panel: ManagedPanel } });
57
+
58
+ function renderScreen(opts: { variant?: 'setup' | 'settings'; configured?: boolean; registry?: AppRegistry } = {}) {
59
+ const screenEl = (
60
+ <SetupScreen settings={settingsWith(opts.configured ?? false)} onSaved={() => {}} variant={opts.variant ?? 'setup'} />
61
+ );
62
+ render(
63
+ opts.registry ? <AppRegistryContext.Provider value={opts.registry}>{screenEl}</AppRegistryContext.Provider> : screenEl,
64
+ );
65
+ }
66
+
67
+ const providerAddress = () => screen.queryByLabelText('Provider address', { exact: false });
68
+
69
+ beforeEach(() => {
70
+ for (const fn of Object.values(api)) fn.mockReset();
71
+ });
72
+
73
+ describe('SetupScreen: what the first run asks', () => {
74
+ it('asks for the repository and for sign-in, and nothing else', () => {
75
+ renderScreen();
76
+ const titles = screen.getAllByRole('heading', { level: 2 }).map((h) => h.textContent);
77
+ expect(titles).toEqual(['Knowledge, skills & tools', 'Single sign-on']);
78
+ });
79
+
80
+ it('keeps every section on the Deployment page', async () => {
81
+ renderScreen({ variant: 'settings' });
82
+ expect(screen.getByRole('heading', { name: 'Audit log' })).toBeInTheDocument();
83
+ expect(await screen.findByRole('heading', { name: 'Marketplace' })).toBeInTheDocument();
84
+ });
85
+ });
86
+
87
+ describe('SetupScreen: a sign-in the distribution runs', () => {
88
+ it('shows no tabs, and the provider form as ever, when the distribution runs none', () => {
89
+ renderScreen();
90
+ expect(screen.queryByRole('tablist')).toBeNull();
91
+ expect(providerAddress()).toBeInTheDocument();
92
+ });
93
+
94
+ it('opens on the tab of the distribution, with the provider form out of the way', () => {
95
+ renderScreen({ registry: hosted });
96
+ const tabs = within(screen.getByRole('tablist')).getAllByRole('tab');
97
+ expect(tabs.map((t) => t.textContent)).toEqual(['Google and Microsoft', 'Your own provider']);
98
+ expect(tabs[0]).toHaveAttribute('aria-selected', 'true');
99
+ expect(screen.getByTestId('managed-panel')).toHaveTextContent('managed sign-in on setup, own provider absent');
100
+ expect(providerAddress()).toBeNull();
101
+ expect(screen.queryByRole('button', { name: 'Test sign-in configuration' })).toBeNull();
102
+ });
103
+
104
+ it('shows the provider form on the second tab, and keeps what was typed across a switch', async () => {
105
+ renderScreen({ registry: hosted });
106
+ await userEvent.click(screen.getByRole('tab', { name: 'Your own provider' }));
107
+ expect(screen.queryByTestId('managed-panel')).toBeNull();
108
+ await userEvent.type(providerAddress()!, 'https://login.example.com');
109
+
110
+ await userEvent.click(screen.getByRole('tab', { name: 'Google and Microsoft' }));
111
+ await userEvent.click(screen.getByRole('tab', { name: 'Your own provider' }));
112
+ expect(providerAddress()).toHaveValue('https://login.example.com');
113
+ });
114
+
115
+ it('opens on the own provider of the deployment once it has one', () => {
116
+ renderScreen({ registry: hosted, configured: true, variant: 'settings' });
117
+ expect(screen.getByRole('tab', { name: 'Your own provider' })).toHaveAttribute('aria-selected', 'true');
118
+ expect(providerAddress()).toBeInTheDocument();
119
+ });
120
+
121
+ it('tells the panel where it stands', async () => {
122
+ renderScreen({ registry: hosted, configured: true, variant: 'settings' });
123
+ await userEvent.click(screen.getByRole('tab', { name: 'Google and Microsoft' }));
124
+ expect(screen.getByTestId('managed-panel')).toHaveTextContent('managed sign-in on settings, own provider configured');
125
+ });
126
+
127
+ it('uses the name the distribution gives the second tab', () => {
128
+ renderScreen({
129
+ registry: makeRegistry({
130
+ signInOption: { label: 'Google and Microsoft', ownProviderLabel: 'Your identity provider', Panel: ManagedPanel },
131
+ }),
132
+ });
133
+ expect(screen.getByRole('tab', { name: 'Your identity provider' })).toBeInTheDocument();
134
+ });
135
+
136
+ /**
137
+ * The panel is the distribution's code, on the screen a deployment cannot
138
+ * be set up without. Its fault costs its own tab: the repository fields,
139
+ * the other tab and the button that finishes setup all stand.
140
+ */
141
+ it('keeps the form when the panel throws, and says so in its place', async () => {
142
+ function BrokenPanel(): never {
143
+ throw new Error('the distribution has a bug');
144
+ }
145
+ // React and the boundary both report the caught error; neither belongs in the run's output.
146
+ const quiet = vi.spyOn(console, 'error').mockImplementation(() => undefined);
147
+ try {
148
+ renderScreen({ registry: makeRegistry({ signInOption: { label: 'Google and Microsoft', Panel: BrokenPanel } }) });
149
+ expect(screen.getByRole('alert')).toHaveTextContent(/sign-in panel couldn.t be shown/);
150
+ expect(screen.getByRole('button', { name: 'Save and continue' })).toBeInTheDocument();
151
+ await userEvent.click(screen.getByRole('tab', { name: 'Your own provider' }));
152
+ expect(providerAddress()).toBeInTheDocument();
153
+ expect(quiet).toHaveBeenCalled();
154
+ } finally {
155
+ quiet.mockRestore();
156
+ }
157
+ });
158
+ });
159
+
160
+ /**
161
+ * A refused save names the fields that were wrong. Every one of those
162
+ * messages has to reach the reader, wherever its field is: a save that
163
+ * failed must never look like a save that did nothing.
164
+ */
165
+ describe('SetupScreen: where a refused save says so', () => {
166
+ const save = () => userEvent.click(screen.getByRole('button', { name: 'Save and continue' }));
167
+
168
+ it('opens the tab a problem is on, and shows it beside its field', async () => {
169
+ api.saveSettings.mockRejectedValue(new SettingsProblems({ oidcClientSecret: 'The provider rejected the application secret.' }));
170
+ renderScreen({ registry: hosted, variant: 'settings' });
171
+ await userEvent.click(screen.getByRole('tab', { name: 'Your own provider' }));
172
+ await userEvent.type(providerAddress()!, 'https://login.example.com');
173
+ await userEvent.click(screen.getByRole('tab', { name: 'Google and Microsoft' }));
174
+ expect(providerAddress()).toBeNull();
175
+
176
+ await save();
177
+ expect(await screen.findByText('The provider rejected the application secret.')).toBeInTheDocument();
178
+ expect(screen.getByRole('tab', { name: 'Your own provider' })).toHaveAttribute('aria-selected', 'true');
179
+ expect(screen.getByLabelText('Application secret', { exact: false })).toHaveAttribute('aria-invalid', 'true');
180
+ });
181
+
182
+ it('leaves the reader on their tab when the problem is somewhere else', async () => {
183
+ api.saveSettings.mockRejectedValue(new SettingsProblems({ kbRepoUrl: 'The URL must start with https://' }));
184
+ renderScreen({ registry: hosted, variant: 'settings' });
185
+ await userEvent.type(screen.getByLabelText('Repository address', { exact: false }), 'git@example.com:kb.git');
186
+ await save();
187
+ expect(await screen.findByText('The URL must start with https://')).toBeInTheDocument();
188
+ expect(screen.getByRole('tab', { name: 'Google and Microsoft' })).toHaveAttribute('aria-selected', 'true');
189
+ });
190
+
191
+ it('says a problem out loud when its field has no place on this screen', async () => {
192
+ // The first run does not show the Audit log section, and a field the
193
+ // environment supplies is not the form's to show anywhere.
194
+ api.saveSettings.mockRejectedValue(
195
+ new SettingsProblems({ auditRetentionDays: 'Enter a number of days.', gitUsername: 'The token username was refused.' }),
196
+ );
197
+ api.testConnection.mockResolvedValue({ ok: true, outcome: 'read-write', branches: ['main'], defaultBranch: 'main' });
198
+ render(
199
+ <SetupScreen
200
+ settings={[...settingsWith(false), setting('gitUsername', 'knowledge-base', { source: 'env', envVar: 'GIT_USERNAME' })]}
201
+ onSaved={() => {}}
202
+ variant="setup"
203
+ />,
204
+ );
205
+ await userEvent.type(screen.getByLabelText('Repository address', { exact: false }), 'https://example.com/kb.git');
206
+ await save();
207
+ const said = await screen.findByText(/Enter a number of days\./);
208
+ expect(said).toHaveTextContent('The token username was refused.');
209
+ });
210
+ });
211
+
212
+ describe('SetupScreen: the form around the distribution panel', () => {
213
+ function PanelWithFields() {
214
+ return (
215
+ <div>
216
+ <input aria-label="Invite by email" />
217
+ <textarea aria-label="A note" />
218
+ </div>
219
+ );
220
+ }
221
+ const withFields = makeRegistry({ signInOption: { label: 'Google and Microsoft', Panel: PanelWithFields } });
222
+
223
+ /**
224
+ * Asserted on the key itself, whose default action IS the submission: a
225
+ * browser submits through the form's button wherever that button sits,
226
+ * and the test environment only through one inside the form, which this
227
+ * form's is not. `fireEvent` answers false when the default was prevented.
228
+ */
229
+ const enterIsLeftToTheForm = (field: HTMLElement) => fireEvent.keyDown(field, { key: 'Enter' });
230
+
231
+ it('is not submitted by Enter in one of the panel inputs', () => {
232
+ renderScreen({ registry: withFields, variant: 'settings' });
233
+ expect(enterIsLeftToTheForm(screen.getByLabelText('Invite by email'))).toBe(false);
234
+ });
235
+
236
+ it('leaves the panel its other keys, and a text area its new line', async () => {
237
+ renderScreen({ registry: withFields, variant: 'settings' });
238
+ expect(fireEvent.keyDown(screen.getByLabelText('Invite by email'), { key: 'a' })).toBe(true);
239
+ expect(enterIsLeftToTheForm(screen.getByLabelText('A note'))).toBe(true);
240
+ await userEvent.type(screen.getByLabelText('A note'), 'one{Enter}two');
241
+ expect(screen.getByLabelText('A note')).toHaveValue('one\ntwo');
242
+ });
243
+
244
+ it('is still submitted by Enter in one of its own fields', async () => {
245
+ renderScreen({ registry: withFields, variant: 'settings' });
246
+ await userEvent.click(screen.getByRole('tab', { name: 'Your own provider' }));
247
+ expect(enterIsLeftToTheForm(providerAddress()!)).toBe(true);
248
+ expect(enterIsLeftToTheForm(screen.getByLabelText('Repository address', { exact: false }))).toBe(true);
249
+ });
250
+ });
251
+
252
+ describe('SetupScreen: what each tab names', () => {
253
+ it.each([
254
+ ['Google and Microsoft', 'managed-panel'],
255
+ ['Your own provider', null],
256
+ ])('gives the tab "%s" a panel of its own', async (name, marker) => {
257
+ renderScreen({ registry: hosted });
258
+ const tab = screen.getByRole('tab', { name });
259
+ await userEvent.click(tab);
260
+ const panel = screen.getByRole('tabpanel');
261
+ expect(panel).toHaveAttribute('id', tab.getAttribute('aria-controls'));
262
+ expect(panel).toHaveAttribute('aria-labelledby', tab.id);
263
+ if (marker) expect(within(panel).getByTestId(marker)).toBeInTheDocument();
264
+ else {
265
+ expect(within(panel).getByLabelText('Provider address', { exact: false })).toBeInTheDocument();
266
+ expect(within(panel).getByText('Redirect URI:', { exact: false })).toBeInTheDocument();
267
+ expect(within(panel).getByRole('button', { name: 'Test sign-in configuration' })).toBeInTheDocument();
268
+ }
269
+ });
270
+
271
+ it('leaves the section as it was when there are no tabs', () => {
272
+ renderScreen();
273
+ expect(screen.queryByRole('tabpanel')).toBeNull();
274
+ expect(screen.getByText('Redirect URI:', { exact: false })).toBeInTheDocument();
275
+ });
276
+ });