@bevel-software/platform-core-frontend 0.22.0 → 0.24.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 (45) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +2 -0
  3. package/src/core/registry.ts +83 -0
  4. package/src/lib/api.ts +49 -0
  5. package/src/modules/access/api.ts +6 -4
  6. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +89 -1
  7. package/src/modules/admin/components/UserAccountsPage.tsx +93 -5
  8. package/src/modules/auth/components/LoginScreen.tsx +3 -0
  9. package/src/modules/auth/services/account.api.ts +26 -3
  10. package/src/modules/change-requests/components/BranchFilePreview.tsx +7 -1
  11. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +89 -10
  12. package/src/modules/git/__tests__/HistoryVersionPreview.test.tsx +479 -0
  13. package/src/modules/git/components/FileHistoryPanel.tsx +52 -65
  14. package/src/modules/git/components/HistoryVersionPreview.tsx +410 -0
  15. package/src/modules/layout/__tests__/ReadOnlyBanner.test.tsx +157 -0
  16. package/src/modules/layout/components/ReadOnlyBanner.tsx +96 -0
  17. package/src/modules/setup/__tests__/setup.repository-change.test.tsx +296 -0
  18. package/src/modules/setup/__tests__/setup.repository.test.tsx +114 -24
  19. package/src/modules/setup/__tests__/setup.test.tsx +5 -3
  20. package/src/modules/setup/components/SetupScreen.tsx +187 -46
  21. package/src/modules/setup/services/setup.api.ts +78 -3
  22. package/src/modules/workspace/components/FileExplorer.tsx +140 -12
  23. package/src/modules/workspace/components/FileViewer.tsx +11 -1
  24. package/src/modules/workspace/components/TreeActionConfirm.tsx +5 -7
  25. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +603 -29
  26. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +23 -6
  27. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +41 -8
  28. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +20 -5
  29. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +39 -16
  30. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +27 -7
  31. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +20 -5
  32. package/src/modules/workspace/components/renderers/RetryReadButton.tsx +37 -0
  33. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +20 -5
  34. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +186 -7
  35. package/src/modules/workspace/components/renderers/__tests__/readPane.test.tsx +59 -0
  36. package/src/modules/workspace/components/renderers/htmlSandbox.ts +80 -20
  37. package/src/modules/workspace/components/renderers/index.ts +6 -1
  38. package/src/modules/workspace/components/renderers/readPane.ts +22 -0
  39. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +50 -9
  40. package/src/modules/workspace/components/renderers/useReadRetry.ts +27 -0
  41. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +79 -0
  42. package/src/modules/workspace/routing/kb-routes.ts +25 -10
  43. package/src/modules/workspace/services/workspace.api.ts +22 -1
  44. package/src/shared/markdown/__tests__/hrefs.test.ts +111 -0
  45. package/src/shared/markdown/hrefs.ts +80 -4
@@ -0,0 +1,157 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { render, screen, waitFor } from '@testing-library/react';
3
+ import { authFetch } from '../../../lib/api';
4
+ import { ReadOnlyBanner } from '../components/ReadOnlyBanner';
5
+
6
+ /**
7
+ * The read-only banner, driven through what the app really does: requests
8
+ * made with `authFetch` against a server that answers. Only `fetch` is
9
+ * replaced, so the path from a refused save to the banner is the real one.
10
+ */
11
+ const READ_ONLY = 'This workspace has 5 people switched on and room for 3.';
12
+
13
+ /** What the server would answer right now. */
14
+ let writable = true;
15
+ /** Every request for the state, so a test can count the asking. */
16
+ let asked = 0;
17
+
18
+ const json = (status: number, body: unknown) =>
19
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
20
+
21
+ beforeEach(() => {
22
+ writable = true;
23
+ asked = 0;
24
+ vi.stubGlobal(
25
+ 'fetch',
26
+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
27
+ const url = String(input);
28
+ if (url === '/api/write-access') {
29
+ asked += 1;
30
+ return json(200, writable ? { writable: true } : { writable: false, message: READ_ONLY });
31
+ }
32
+ // The account routes stay open while the deployment is read-only.
33
+ if (url.startsWith('/api/admin/accounts')) return json(200, {});
34
+ if ((init?.method ?? 'GET') === 'GET') return json(200, {});
35
+ return writable ? json(200, {}) : json(403, { error: READ_ONLY, code: 'workspace_read_only' });
36
+ }),
37
+ );
38
+ });
39
+
40
+ afterEach(() => {
41
+ vi.unstubAllGlobals();
42
+ vi.useRealTimers();
43
+ });
44
+
45
+ describe('ReadOnlyBanner', () => {
46
+ it('says so, in the host’s words, on a deployment that is read-only when the app opens', async () => {
47
+ writable = false;
48
+ render(<ReadOnlyBanner />);
49
+ expect(await screen.findByRole('status')).toHaveTextContent(READ_ONLY);
50
+ });
51
+
52
+ it('shows nothing on a writable deployment, and asks once, however long the tab stays open', async () => {
53
+ vi.useFakeTimers({ shouldAdvanceTime: true });
54
+ render(<ReadOnlyBanner />);
55
+ await waitFor(() => expect(asked).toBe(1));
56
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
57
+ expect(asked).toBe(1);
58
+ expect(screen.queryByRole('status')).toBeNull();
59
+ });
60
+
61
+ it('learns the deployment went read-only from the first change that is refused', async () => {
62
+ render(<ReadOnlyBanner />);
63
+ await waitFor(() => expect(asked).toBe(1));
64
+ expect(screen.queryByRole('status')).toBeNull();
65
+
66
+ writable = false;
67
+ const refused = await authFetch('/api/workspace/w1/file', { method: 'PUT', body: '{}' });
68
+ // The caller still has the answer to itself.
69
+ expect(await refused.json()).toMatchObject({ code: 'workspace_read_only' });
70
+ expect(await screen.findByRole('status')).toHaveTextContent(READ_ONLY);
71
+ });
72
+
73
+ it('is not moved by a refusal that is about something else', async () => {
74
+ render(<ReadOnlyBanner />);
75
+ await waitFor(() => expect(asked).toBe(1));
76
+ vi.mocked(fetch).mockResolvedValueOnce(json(403, { error: 'You cannot edit this file.' }));
77
+ await authFetch('/api/workspace/w1/file', { method: 'PUT', body: '{}' });
78
+ await new Promise((resolve) => setTimeout(resolve, 20));
79
+ expect(asked).toBe(1);
80
+ });
81
+
82
+ it('goes away once an admin’s change ends the state', async () => {
83
+ vi.useFakeTimers({ shouldAdvanceTime: true });
84
+ writable = false;
85
+ render(<ReadOnlyBanner />);
86
+ await screen.findByRole('status');
87
+ // Some while later, so the check is made at once and not spaced.
88
+ await vi.advanceTimersByTimeAsync(30_000);
89
+
90
+ // The admin switches an account off: the request succeeds, and the count is back under the plan.
91
+ writable = true;
92
+ await authFetch('/api/admin/accounts/u1/deactivate', { method: 'POST' });
93
+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull());
94
+ expect(asked).toBe(2);
95
+ });
96
+
97
+ it('does not ask again over changes that go through while nothing is wrong', async () => {
98
+ render(<ReadOnlyBanner />);
99
+ await waitFor(() => expect(asked).toBe(1));
100
+ await authFetch('/api/workspace/w1/file', { method: 'PUT', body: '{}' });
101
+ await authFetch('/api/workspace/w1/file', { method: 'PUT', body: '{}' });
102
+ await new Promise((resolve) => setTimeout(resolve, 20));
103
+ expect(asked).toBe(1);
104
+ });
105
+
106
+ it('asks again when the tab comes back into view, at most once a minute, and never as it leaves', async () => {
107
+ vi.useFakeTimers({ shouldAdvanceTime: true });
108
+ let visibility: DocumentVisibilityState = 'visible';
109
+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });
110
+ const turn = (to: DocumentVisibilityState) => {
111
+ visibility = to;
112
+ document.dispatchEvent(new Event('visibilitychange'));
113
+ };
114
+ try {
115
+ render(<ReadOnlyBanner />);
116
+ await waitFor(() => expect(asked).toBe(1));
117
+
118
+ // Back into view too soon after the last check.
119
+ turn('hidden');
120
+ turn('visible');
121
+ expect(asked).toBe(1);
122
+
123
+ await vi.advanceTimersByTimeAsync(61_000);
124
+ writable = false;
125
+ // Leaving the tab asks nothing, however long it has been.
126
+ turn('hidden');
127
+ expect(asked).toBe(1);
128
+ turn('visible');
129
+ expect(await screen.findByRole('status')).toHaveTextContent(READ_ONLY);
130
+ expect(asked).toBe(2);
131
+ } finally {
132
+ Reflect.deleteProperty(document, 'visibilityState');
133
+ }
134
+ });
135
+
136
+ /**
137
+ * A permission lookup or a heartbeat is a POST that goes through, and the
138
+ * app makes them all the time. They must not turn into a check each.
139
+ */
140
+ it('spaces the checks that requests going through set off, without losing the last one', async () => {
141
+ vi.useFakeTimers({ shouldAdvanceTime: true });
142
+ writable = false;
143
+ render(<ReadOnlyBanner />);
144
+ await screen.findByRole('status');
145
+ expect(asked).toBe(1);
146
+
147
+ for (let i = 0; i < 5; i += 1) await authFetch('/api/admin/accounts/lookup', { method: 'POST' });
148
+ expect(asked).toBe(1);
149
+
150
+ // The change that ends the state arrives inside the spacing, and is still asked about.
151
+ writable = true;
152
+ await authFetch('/api/admin/accounts/u1/deactivate', { method: 'POST' });
153
+ await vi.advanceTimersByTimeAsync(5_000);
154
+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull());
155
+ expect(asked).toBe(2);
156
+ });
157
+ });
@@ -0,0 +1,96 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { Lock } from 'lucide-react';
3
+ import { authFetch, WRITE_ACCEPTED_EVENT, WRITE_REFUSED_EVENT } from '../../../lib/api';
4
+ import { useLatestRef } from '../../../shared/components/useLatestRef';
5
+
6
+ /** The least time between two checks made because the tab came back into view. */
7
+ const RETURN_CHECK_MS = 60_000;
8
+
9
+ /** The least time between two checks made because a request went through while the banner is up. */
10
+ const ACCEPTED_CHECK_MS = 5_000;
11
+
12
+ /**
13
+ * App-wide notice that the deployment is read-only right now (`GET
14
+ * /api/write-access`): everyone can still sign in and read, but every change
15
+ * is refused until the cause is fixed — on a host that sells seats, more
16
+ * people are switched on than the plan allows. Said once, here, with the
17
+ * host's own words, instead of letting each save fail on its own.
18
+ *
19
+ * Renders nothing while the deployment is writable, which on a core
20
+ * deployment is always.
21
+ *
22
+ * ASKED ON ACTIVITY, NEVER ON A TIMER. Once when the app opens; when a
23
+ * change is refused as read-only, which is how an open tab learns the state
24
+ * began; when the tab comes back into view; and, while the banner is up,
25
+ * when a change goes through, which is how it learns the state ended (an
26
+ * admin switching accounts off). An idle tab on a deployment that can never
27
+ * be read-only asks once and never again.
28
+ */
29
+ export function ReadOnlyBanner() {
30
+ const [message, setMessage] = useState<string | null>(null);
31
+ const showing = useLatestRef(message !== null);
32
+
33
+ useEffect(() => {
34
+ let cancelled = false;
35
+ // Only the latest check may decide: a slow answer to an earlier one must
36
+ // not overwrite what a newer one said.
37
+ let latest = 0;
38
+ let lastAsked = 0;
39
+ const check = () => {
40
+ const mine = ++latest;
41
+ lastAsked = Date.now();
42
+ authFetch('/api/write-access')
43
+ .then((res) => (res.ok ? res.json() : { writable: true }))
44
+ .then((body: { writable?: boolean; message?: string }) => {
45
+ if (cancelled || mine !== latest) return;
46
+ setMessage(body.writable === false ? (body.message ?? 'This workspace is read-only.') : null);
47
+ })
48
+ // An unanswered check says nothing about the workspace; keep what we knew.
49
+ .catch(() => undefined);
50
+ };
51
+ const onReturn = () => {
52
+ if (document.visibilityState === 'visible' && Date.now() - lastAsked >= RETURN_CHECK_MS) check();
53
+ };
54
+ // Requests that only ask something are POSTs too (a permission lookup,
55
+ // a heartbeat), and the app makes them constantly. So the checks they
56
+ // set off are spaced: one now if none was made lately, otherwise ONE
57
+ // later, at the end of the spacing, so the change that did end the state
58
+ // is never the one that went unasked about.
59
+ let pending: number | null = null;
60
+ const onAccepted = () => {
61
+ if (!showing.current || pending !== null) return;
62
+ const wait = ACCEPTED_CHECK_MS - (Date.now() - lastAsked);
63
+ if (wait <= 0) return check();
64
+ pending = window.setTimeout(() => {
65
+ pending = null;
66
+ if (showing.current) check();
67
+ }, wait);
68
+ };
69
+ check();
70
+ window.addEventListener(WRITE_REFUSED_EVENT, check);
71
+ window.addEventListener(WRITE_ACCEPTED_EVENT, onAccepted);
72
+ document.addEventListener('visibilitychange', onReturn);
73
+ return () => {
74
+ cancelled = true;
75
+ if (pending !== null) window.clearTimeout(pending);
76
+ window.removeEventListener(WRITE_REFUSED_EVENT, check);
77
+ window.removeEventListener(WRITE_ACCEPTED_EVENT, onAccepted);
78
+ document.removeEventListener('visibilitychange', onReturn);
79
+ };
80
+ }, [showing]);
81
+ // `showing` is a ref with a stable identity: the effect runs once.
82
+
83
+ if (message === null) return null;
84
+
85
+ return (
86
+ <div
87
+ role="status"
88
+ className="flex items-center gap-2 px-4 py-2 border-b border-line text-sm shrink-0 bg-wait-soft text-ink"
89
+ >
90
+ <Lock size={16} className="shrink-0" />
91
+ <span className="flex-1">
92
+ <span className="font-semibold">Read-only.</span> {message}
93
+ </span>
94
+ </div>
95
+ );
96
+ }
@@ -0,0 +1,296 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { render, screen, waitFor } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+
5
+ /**
6
+ * Pointing the deployment at a DIFFERENT knowledge-base repository.
7
+ *
8
+ * The server refuses such a save until it is confirmed, because confirming it
9
+ * is the only warning anyone gets: every working copy on the server stops
10
+ * being used and is cloned fresh, and anything committed there and never
11
+ * pushed goes out of the app with it. When change requests are open the same
12
+ * confirmation says how many and asks what to do with them.
13
+ *
14
+ * Only the transport is mocked, so what is under test is the whole path from
15
+ * the button to the request bodies the form sends.
16
+ */
17
+ const transport = vi.hoisted(() => ({ authFetch: vi.fn() }));
18
+ vi.mock('../../../lib/api', async (importOriginal) => ({
19
+ ...(await importOriginal<typeof import('../../../lib/api')>()),
20
+ authFetch: transport.authFetch,
21
+ }));
22
+
23
+ const facade = vi.hoisted(() => ({
24
+ fetchGitHubFacade: vi.fn(),
25
+ rotateGitHubFacade: vi.fn(),
26
+ fetchMarketplaceRegistration: vi.fn(async () => false),
27
+ setMarketplaceRegistration: vi.fn(),
28
+ }));
29
+ vi.mock('../../settings/services/github-facade.api', () => facade);
30
+
31
+ import { SetupScreen } from '../components/SetupScreen';
32
+ import type { SettingStatus } from '../services/setup.api';
33
+
34
+ const KB = 'knowledge-base' as const;
35
+ const CONFIGURED = 'https://example.com/acme/kb.git';
36
+ const REPLACEMENT = 'https://example.com/acme/replacement.git';
37
+
38
+ /** A deployment that has been running against CONFIGURED for a while. */
39
+ const SETTINGS: SettingStatus[] = [
40
+ { key: 'kbRepoUrl', envVar: 'KB_REPO_URL', section: KB, source: 'stored', value: CONFIGURED, configured: true, secret: false, restartToApply: false },
41
+ { key: 'gitToken', envVar: 'GIT_TOKEN', section: KB, source: 'stored', configured: true, secret: true, restartToApply: false },
42
+ { key: 'gitUsername', envVar: 'GIT_USERNAME', section: KB, source: 'unset', value: '', configured: false, secret: false, restartToApply: false },
43
+ { key: 'defaultBranch', envVar: 'DEFAULT_BRANCH', section: KB, source: 'stored', value: 'main', configured: true, secret: false, restartToApply: true },
44
+ { key: 'protectedBranches', envVar: 'PROTECTED_BRANCHES', section: KB, source: 'stored', value: 'main', configured: true, secret: false, restartToApply: true },
45
+ ];
46
+
47
+ const json = (status: number, body: unknown) =>
48
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
49
+
50
+ /** The bodies of every POST to the save endpoint, oldest first. */
51
+ const saveBodies = (): Array<Record<string, unknown>> =>
52
+ transport.authFetch.mock.calls
53
+ .filter(([url]) => String(url) === '/api/setup/settings')
54
+ .map(([, init]) => JSON.parse(String((init as RequestInit).body)) as Record<string, unknown>);
55
+
56
+ /**
57
+ * The server: the remote answers for the new address, and the save is refused
58
+ * with a 409 until a confirmation rides along.
59
+ */
60
+ function serverWith(openChangeRequests: number) {
61
+ transport.authFetch.mockImplementation(async (url: string, init?: RequestInit) => {
62
+ if (url === '/api/setup/test-connection') {
63
+ return json(200, { ok: true, outcome: 'connected', branches: ['main'], defaultBranch: 'main', empty: false });
64
+ }
65
+ if (url === '/api/setup/settings') {
66
+ const body = JSON.parse(String(init?.body ?? '{}')) as { confirmRepositoryChange?: string };
67
+ if (!body.confirmRepositoryChange) {
68
+ return json(409, {
69
+ error: 'This moves the deployment to another repository.',
70
+ repositoryChange: { openChangeRequests },
71
+ });
72
+ }
73
+ return json(200, {
74
+ ok: true,
75
+ restartRequired: false,
76
+ complete: true,
77
+ settings: SETTINGS,
78
+ repositoryChange: {
79
+ choice: body.confirmRepositoryChange,
80
+ closedChangeRequests: body.confirmRepositoryChange === 'close' ? openChangeRequests : 0,
81
+ },
82
+ });
83
+ }
84
+ return json(404, { error: 'not mocked' });
85
+ });
86
+ }
87
+
88
+ /** Type the new address into a rendered settings form and press Save. */
89
+ async function typeTheNewAddressAndSave() {
90
+ const url = screen.getByLabelText('Repository address');
91
+ await userEvent.clear(url);
92
+ await userEvent.type(url, REPLACEMENT);
93
+ await userEvent.type(screen.getByLabelText('Access token'), 'ghp_new');
94
+ await userEvent.click(screen.getByRole('button', { name: 'Save and continue' }));
95
+ }
96
+
97
+ beforeEach(() => {
98
+ transport.authFetch.mockReset();
99
+ Object.defineProperty(window, 'location', {
100
+ configurable: true,
101
+ value: { ...window.location, reload: vi.fn(), origin: 'https://example.test' },
102
+ });
103
+ });
104
+
105
+ describe('a changed repository address, with change requests open', () => {
106
+ it('asks before saving: what is replaced, what is lost, and how many requests', async () => {
107
+ serverWith(2);
108
+ render(<SetupScreen settings={SETTINGS} onSaved={vi.fn()} variant="settings" />);
109
+
110
+ await typeTheNewAddressAndSave();
111
+
112
+ const confirm = await screen.findByTestId('repository-change-confirm');
113
+ expect(confirm).toHaveTextContent(/stops being used and is cloned fresh/i);
114
+ // The warning has to name the cost, and name it truthfully: the copies are
115
+ // set aside on the server, so the work is out of the app but not destroyed.
116
+ expect(confirm).toHaveTextContent(/not yet pushed from this server goes out of the app/i);
117
+ expect(confirm).toHaveTextContent(/nothing is deleted/i);
118
+ expect(confirm).toHaveTextContent(/replaced-working-copies/);
119
+ expect(confirm).toHaveTextContent('There are 2 open change requests.');
120
+ // Two choices, and keeping them is the one already selected: nothing
121
+ // closes by hesitating.
122
+ const [keep, close] = screen.getAllByRole('radio');
123
+ expect(keep).toBeChecked();
124
+ expect(close).not.toBeChecked();
125
+ });
126
+
127
+ it('keeps them when the admin says the repository only moved', async () => {
128
+ serverWith(2);
129
+ render(<SetupScreen settings={SETTINGS} onSaved={vi.fn()} variant="settings" />);
130
+ await typeTheNewAddressAndSave();
131
+ await screen.findByTestId('repository-change-confirm');
132
+
133
+ await userEvent.click(screen.getByRole('button', { name: 'Move the deployment' }));
134
+
135
+ await waitFor(() => expect(saveBodies()).toHaveLength(2));
136
+ expect(saveBodies()[1]).toMatchObject({
137
+ confirmRepositoryChange: 'keep',
138
+ settings: { kbRepoUrl: REPLACEMENT },
139
+ });
140
+ expect(await screen.findByTestId('repository-changed')).toHaveTextContent(/now works on the new repository/i);
141
+ });
142
+
143
+ it('closes them as “repository replaced” when the admin picks that, and says so', async () => {
144
+ serverWith(2);
145
+ render(<SetupScreen settings={SETTINGS} onSaved={vi.fn()} variant="settings" />);
146
+ await typeTheNewAddressAndSave();
147
+ await screen.findByTestId('repository-change-confirm');
148
+
149
+ await userEvent.click(screen.getAllByRole('radio')[1]!);
150
+ await userEvent.click(screen.getByRole('button', { name: 'Move the deployment' }));
151
+
152
+ await waitFor(() => expect(saveBodies()).toHaveLength(2));
153
+ expect(saveBodies()[1]).toMatchObject({ confirmRepositoryChange: 'close' });
154
+ const done = await screen.findByTestId('repository-changed');
155
+ expect(done).toHaveTextContent('2 change requests were closed as “repository replaced”.');
156
+ expect(done).toHaveTextContent('Nothing was deleted.');
157
+ });
158
+
159
+ it('cancelling saves nothing and leaves the typed address on screen', async () => {
160
+ serverWith(2);
161
+ render(<SetupScreen settings={SETTINGS} onSaved={vi.fn()} variant="settings" />);
162
+ await typeTheNewAddressAndSave();
163
+ await screen.findByTestId('repository-change-confirm');
164
+
165
+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
166
+
167
+ expect(screen.queryByTestId('repository-change-confirm')).not.toBeInTheDocument();
168
+ // One refused attempt, and nothing since.
169
+ expect(saveBodies()).toHaveLength(1);
170
+ expect(screen.getByLabelText('Repository address')).toHaveValue(REPLACEMENT);
171
+ });
172
+ });
173
+
174
+ describe('a changed repository address with nothing open', () => {
175
+ it('still warns about the working copies, and offers no choice it cannot honour', async () => {
176
+ serverWith(0);
177
+ render(<SetupScreen settings={SETTINGS} onSaved={vi.fn()} variant="settings" />);
178
+ await typeTheNewAddressAndSave();
179
+
180
+ const confirm = await screen.findByTestId('repository-change-confirm');
181
+ expect(confirm).toHaveTextContent(/stops being used and is cloned fresh/i);
182
+ expect(screen.queryAllByRole('radio')).toEqual([]);
183
+
184
+ await userEvent.click(screen.getByRole('button', { name: 'Move the deployment' }));
185
+ await waitFor(() => expect(saveBodies()).toHaveLength(2));
186
+ expect(saveBodies()[1]).toMatchObject({ confirmRepositoryChange: 'keep' });
187
+ });
188
+ });
189
+
190
+ describe('a CONFIRMED save the server refuses', () => {
191
+ /**
192
+ * The probe passed and the confirmation was answered, and the store step
193
+ * still failed — a token revoked in between, a repository that went away, a
194
+ * close that could not be done. The admin has just agreed to lose their
195
+ * working copies; being told only that it "did not save" is the worst moment
196
+ * for that.
197
+ */
198
+ it('shows the reason the server gave for refusing the confirmed save', async () => {
199
+ transport.authFetch.mockImplementation(async (url: string, init?: RequestInit) => {
200
+ if (url === '/api/setup/test-connection') {
201
+ return json(200, { ok: true, outcome: 'connected', branches: ['main'], defaultBranch: 'main', empty: false });
202
+ }
203
+ if (url === '/api/setup/settings') {
204
+ const body = JSON.parse(String(init?.body ?? '{}')) as { confirmRepositoryChange?: string };
205
+ if (!body.confirmRepositoryChange) {
206
+ return json(409, {
207
+ error: 'This moves the deployment to another repository.',
208
+ repositoryChange: { openChangeRequests: 2 },
209
+ });
210
+ }
211
+ return json(500, {
212
+ error:
213
+ 'The open change requests could not be closed, so the repository was not changed. ' +
214
+ 'Nothing was saved and no working copy was touched. Try again.',
215
+ });
216
+ }
217
+ return json(404, { error: 'not mocked' });
218
+ });
219
+ render(<SetupScreen settings={SETTINGS} onSaved={vi.fn()} variant="settings" />);
220
+ await typeTheNewAddressAndSave();
221
+ await screen.findByTestId('repository-change-confirm');
222
+
223
+ await userEvent.click(screen.getAllByRole('radio')[1]!);
224
+ await userEvent.click(screen.getByRole('button', { name: 'Move the deployment' }));
225
+
226
+ expect(
227
+ await screen.findByText(/The open change requests could not be closed/),
228
+ ).toBeInTheDocument();
229
+ // And nothing claims the repository was replaced.
230
+ expect(screen.queryByTestId('repository-changed')).not.toBeInTheDocument();
231
+ });
232
+
233
+ /**
234
+ * The address IS stored and it is the initialization that failed. The
235
+ * confirmation has been answered and must go: left standing over a cleared
236
+ * draft, its Replace button would re-send the stored address, change
237
+ * nothing, and lose the "requests closed" outcome for good. The init banner
238
+ * owns the retry from here.
239
+ */
240
+ it('takes the confirmation down when the save stored the address but initialization failed', async () => {
241
+ transport.authFetch.mockImplementation(async (url: string, init?: RequestInit) => {
242
+ if (url === '/api/setup/test-connection') {
243
+ return json(200, { ok: true, outcome: 'connected', branches: ['main'], defaultBranch: 'main', empty: false });
244
+ }
245
+ if (url === '/api/setup/settings') {
246
+ const body = JSON.parse(String(init?.body ?? '{}')) as { confirmRepositoryChange?: string };
247
+ if (!body.confirmRepositoryChange) {
248
+ return json(409, {
249
+ error: 'This moves the deployment to another repository.',
250
+ repositoryChange: { openChangeRequests: 1 },
251
+ });
252
+ }
253
+ return json(500, {
254
+ error: 'The knowledge base could not be initialized.',
255
+ kbInit: { kind: 'not-found', cause: 'There is no repository at that address.' },
256
+ });
257
+ }
258
+ return json(404, { error: 'not mocked' });
259
+ });
260
+ render(<SetupScreen settings={SETTINGS} onSaved={vi.fn()} variant="settings" />);
261
+ await typeTheNewAddressAndSave();
262
+ await screen.findByTestId('repository-change-confirm');
263
+
264
+ await userEvent.click(screen.getByRole('button', { name: 'Move the deployment' }));
265
+
266
+ await waitFor(() =>
267
+ expect(screen.queryByTestId('repository-change-confirm')).not.toBeInTheDocument(),
268
+ );
269
+ expect(screen.queryByRole('button', { name: 'Move the deployment' })).toBeNull();
270
+ expect(await screen.findByText(/There is no repository at that address\./)).toBeInTheDocument();
271
+ // Two requests went out; nothing re-sent the answered confirmation.
272
+ expect(saveBodies()).toHaveLength(2);
273
+ });
274
+ });
275
+
276
+ describe('a save the server refuses', () => {
277
+ it('shows the reason the server gave, not only that it did not save', async () => {
278
+ transport.authFetch.mockImplementation(async (url: string) => {
279
+ if (url === '/api/setup/test-connection') {
280
+ return json(400, {
281
+ ok: false,
282
+ error: 'There is no repository at that address, or the token cannot see it.',
283
+ });
284
+ }
285
+ return json(404, { error: 'not mocked' });
286
+ });
287
+ render(<SetupScreen settings={SETTINGS} onSaved={vi.fn()} variant="settings" />);
288
+
289
+ await typeTheNewAddressAndSave();
290
+
291
+ // "Not saved" alone leaves an admin rereading a form that looks correct.
292
+ const banner = await screen.findByText(/Not saved\./);
293
+ expect(banner).toHaveTextContent('There is no repository at that address, or the token cannot see it.');
294
+ expect(saveBodies()).toEqual([]);
295
+ });
296
+ });