@bevel-software/platform-core-frontend 0.7.5 → 0.9.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 (132) hide show
  1. package/LICENSE +202 -202
  2. package/THIRD-PARTY-NOTICES.md +344 -988
  3. package/package.json +5 -5
  4. package/src/core/CoreAppShell.tsx +4 -4
  5. package/src/core/__tests__/ShellRoutes.test.tsx +1 -1
  6. package/src/core/__tests__/bootstrap.test.ts +47 -2
  7. package/src/core/bootstrap.ts +20 -0
  8. package/src/core/registry.ts +16 -4
  9. package/src/css-side-effect-imports.d.ts +7 -7
  10. package/src/modules/access/__tests__/ManageAccessDialog.placement.test.tsx +1 -1
  11. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +5 -5
  12. package/src/modules/access/api.ts +5 -5
  13. package/src/modules/access/components/ManageAccessDialog.tsx +21 -20
  14. package/src/modules/admin/__tests__/AdminRolesPage.suggest.test.tsx +1 -1
  15. package/src/modules/admin/components/AdminRolesPage.tsx +1 -1
  16. package/src/modules/admin/state/admin.context.tsx +15 -0
  17. package/src/modules/change-requests/__tests__/useFileOnBranch.test.tsx +2 -2
  18. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +1 -1
  19. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +1 -1
  20. package/src/modules/layout/__tests__/SidebarFrameResponsive.test.tsx +4 -4
  21. package/src/modules/layout/__tests__/SidebarToggle.test.tsx +4 -4
  22. package/src/modules/layout/__tests__/breakpoints.test.ts +1 -1
  23. package/src/modules/layout/components/SidebarFrame.tsx +2 -2
  24. package/src/modules/library/__tests__/{AddToGroupDialog.test.tsx → AddToPluginDialog.test.tsx} +34 -34
  25. package/src/modules/library/__tests__/LibraryCard.test.tsx +30 -11
  26. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +84 -59
  27. package/src/modules/library/__tests__/LibrarySidebarMenu.test.tsx +51 -51
  28. package/src/modules/library/__tests__/{LockedGroupView.test.tsx → LockedPluginView.test.tsx} +33 -33
  29. package/src/modules/library/__tests__/McpServerSection.test.tsx +138 -0
  30. package/src/modules/library/__tests__/{NewGroupDialog.test.tsx → NewPluginDialog.test.tsx} +22 -22
  31. package/src/modules/library/__tests__/PersonalAddDialog.test.tsx +7 -7
  32. package/src/modules/library/__tests__/PluginExtras.test.tsx +131 -0
  33. package/src/modules/library/__tests__/{GroupJoinRequests.test.tsx → PluginJoinRequests.test.tsx} +24 -24
  34. package/src/modules/library/__tests__/{GroupPage.test.tsx → PluginPage.test.tsx} +197 -106
  35. package/src/modules/library/__tests__/PluginsIndexPage.test.tsx +363 -0
  36. package/src/modules/library/__tests__/{GroupsSidebar.contextmenu.test.tsx → PluginsSidebar.contextmenu.test.tsx} +32 -31
  37. package/src/modules/library/__tests__/{GroupsSidebar.locked.test.tsx → PluginsSidebar.locked.test.tsx} +29 -28
  38. package/src/modules/library/__tests__/PluginsSidebar.test.tsx +171 -0
  39. package/src/modules/library/__tests__/{GroupsSidebarMenu.test.tsx → PluginsSidebarMenu.test.tsx} +18 -18
  40. package/src/modules/library/__tests__/SkillPage.test.tsx +8 -8
  41. package/src/modules/library/__tests__/ToolConnectionSection.test.tsx +2 -2
  42. package/src/modules/library/__tests__/ToolPage.test.tsx +41 -12
  43. package/src/modules/library/__tests__/ToolSharePanel.test.tsx +1 -1
  44. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +57 -57
  45. package/src/modules/library/__tests__/auth-harness.tsx +4 -4
  46. package/src/modules/library/__tests__/library-data.test.ts +82 -0
  47. package/src/modules/library/__tests__/status.test.ts +19 -19
  48. package/src/modules/library/__tests__/tools.api.test.ts +70 -0
  49. package/src/modules/library/__tests__/useToolPage.test.tsx +4 -4
  50. package/src/modules/library/components/AccessRequestsBanner.tsx +8 -8
  51. package/src/modules/library/components/{AddToGroupDialog.tsx → AddToPluginDialog.tsx} +11 -11
  52. package/src/modules/library/components/ChangeRequestDock.tsx +1 -1
  53. package/src/modules/library/components/{DeleteGroupDialog.tsx → DeletePluginDialog.tsx} +9 -9
  54. package/src/modules/library/components/LibraryCard.tsx +26 -2
  55. package/src/modules/library/components/LibraryLayout.tsx +80 -71
  56. package/src/modules/library/components/LibraryPage.tsx +8 -8
  57. package/src/modules/library/components/LockGlyph.tsx +1 -1
  58. package/src/modules/library/components/{LockedGroupView.tsx → LockedPluginView.tsx} +35 -35
  59. package/src/modules/library/components/{ManagedGroupRequests.tsx → ManagedPluginRequests.tsx} +13 -13
  60. package/src/modules/library/components/{NewGroupDialog.tsx → NewPluginDialog.tsx} +24 -24
  61. package/src/modules/library/components/NewSkillPanel.tsx +23 -5
  62. package/src/modules/library/components/PageActions.tsx +34 -11
  63. package/src/modules/library/components/PersonalAddDialog.tsx +5 -5
  64. package/src/modules/library/components/{PersonalGroupPage.tsx → PersonalPluginPage.tsx} +29 -19
  65. package/src/modules/library/components/PluginExtras.tsx +195 -0
  66. package/src/modules/library/components/{GroupIndexRow.tsx → PluginIndexRow.tsx} +6 -6
  67. package/src/modules/library/components/PluginJoinRequests.tsx +77 -0
  68. package/src/modules/library/components/{GroupPage.tsx → PluginPage.tsx} +112 -72
  69. package/src/modules/library/components/{GroupsIndexPage.tsx → PluginsIndexPage.tsx} +91 -48
  70. package/src/modules/library/components/{GroupsSidebar.tsx → PluginsSidebar.tsx} +105 -55
  71. package/src/modules/library/components/{GroupsSidebarMenu.tsx → PluginsSidebarMenu.tsx} +15 -15
  72. package/src/modules/library/components/{group-page-parts.tsx → plugin-page-parts.tsx} +218 -27
  73. package/src/modules/library/components/skill-page/SkillPage.tsx +12 -12
  74. package/src/modules/library/components/tool-page/McpServerSection.tsx +380 -0
  75. package/src/modules/library/components/tool-page/ToolPage.tsx +22 -5
  76. package/src/modules/library/hooks/useJoinRequests.ts +8 -8
  77. package/src/modules/library/routes/LibraryRoutes.tsx +32 -19
  78. package/src/modules/library/routes/WorkspaceItemRoute.tsx +24 -24
  79. package/src/modules/library/routes/library-paths.ts +36 -36
  80. package/src/modules/library/services/library.api.ts +9 -9
  81. package/src/modules/library/services/{groups.api.ts → plugins.api.ts} +43 -43
  82. package/src/modules/library/services/tools.api.ts +54 -0
  83. package/src/modules/library/state/library-data.tsx +67 -46
  84. package/src/modules/library/utils/names.ts +1 -1
  85. package/src/modules/library/utils/{personal-group.ts → personal-plugin.ts} +8 -8
  86. package/src/modules/library/utils/{group-summary.ts → plugin-summary.ts} +14 -14
  87. package/src/modules/library/utils/status.ts +17 -17
  88. package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +318 -0
  89. package/src/modules/onboarding/__tests__/onboarding.test.tsx +86 -8
  90. package/src/modules/onboarding/agent-clients.ts +18 -14
  91. package/src/modules/onboarding/components/CreatorWelcomePage.tsx +143 -0
  92. package/src/modules/onboarding/components/WelcomePage.tsx +30 -22
  93. package/src/modules/onboarding/components/WelcomeRoute.tsx +57 -0
  94. package/src/modules/onboarding/welcome-state.ts +36 -0
  95. package/src/modules/review/components/MarkdownDiffViewer.tsx +1 -1
  96. package/src/modules/review/components/ReviewPanel.tsx +11 -11
  97. package/src/modules/review/components/__tests__/{isGroupItemPath.test.ts → isPluginItemPath.test.ts} +24 -24
  98. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +3 -3
  99. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +1 -1
  100. package/src/modules/settings/components/SettingsLayout.tsx +1 -1
  101. package/src/modules/settings/components/SettingsNav.tsx +5 -5
  102. package/src/modules/setup/__tests__/setup.test.tsx +203 -0
  103. package/src/modules/setup/components/SetupScreen.tsx +235 -68
  104. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +29 -107
  105. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +1 -1
  106. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +228 -0
  107. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +3 -3
  108. package/src/modules/workspace/components/FileExplorer.tsx +12 -12
  109. package/src/modules/workspace/components/FileRoute.tsx +8 -1
  110. package/src/modules/workspace/components/FileViewer.tsx +95 -38
  111. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +14 -14
  112. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +20 -0
  113. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +227 -18
  114. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +7 -2
  115. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +25 -0
  116. package/src/modules/workspace/routing/kb-routes.ts +23 -1
  117. package/src/modules/workspace/utils/__tests__/diff.test.ts +1 -1
  118. package/src/modules/workspace/utils/fileTree.ts +54 -3
  119. package/src/shared/components/Surface.tsx +15 -0
  120. package/src/shared/mcp/ClaudeInstallLink.tsx +88 -0
  121. package/src/shared/mcp/ConnectionInstructions.tsx +51 -0
  122. package/src/shared/mcp/CopyBlock.tsx +42 -0
  123. package/src/shared/mcp/__tests__/ClaudeInstallLink.test.tsx +40 -0
  124. package/src/shared/mcp/__tests__/connect-snippets.test.ts +431 -0
  125. package/src/shared/mcp/__tests__/useCopyFeedback.test.ts +112 -0
  126. package/src/shared/mcp/connect-snippets.ts +353 -0
  127. package/src/shared/mcp/index.ts +28 -0
  128. package/src/shared/mcp/useCopyFeedback.ts +46 -0
  129. package/src/test-setup.ts +11 -0
  130. package/src/modules/library/__tests__/GroupsIndexPage.test.tsx +0 -283
  131. package/src/modules/library/__tests__/GroupsSidebar.test.tsx +0 -142
  132. package/src/modules/library/components/GroupJoinRequests.tsx +0 -56
@@ -141,6 +141,209 @@ describe('SetupScreen', () => {
141
141
  expect(await screen.findByText(/rejected those credentials/)).toBeInTheDocument();
142
142
  });
143
143
 
144
+ /**
145
+ * A REJECTED CONNECTION MUST NOT FINISH SETUP.
146
+ *
147
+ * The server's completeness check asks whether the answers are present, not
148
+ * whether they work — so a token the host turns down finishes setup exactly
149
+ * as well as one it accepts, and the gate opens onto an app whose every call
150
+ * fails against a repository it cannot clone. Someone who has just been told
151
+ * the credentials are wrong could still press the button that let them in.
152
+ */
153
+ it('will not let a rejected connection through to the app', async () => {
154
+ await renderScreen();
155
+ api.testConnection.mockResolvedValue({
156
+ ok: false,
157
+ error: 'The host rejected those credentials.',
158
+ });
159
+ await userEvent.type(screen.getByLabelText('Repository address'), 'https://x/y.git');
160
+ await userEvent.type(screen.getByLabelText('Access token'), 'ghp_wrong');
161
+ await userEvent.click(screen.getByRole('button', { name: 'Test connection' }));
162
+ await screen.findByText(/rejected those credentials/);
163
+
164
+ expect(screen.getByRole('button', { name: 'Save and continue' })).toBeDisabled();
165
+ expect(screen.getByText(/turned that connection down/)).toBeInTheDocument();
166
+ expect(api.saveSettings).not.toHaveBeenCalled();
167
+ expect(reload).not.toHaveBeenCalled();
168
+ });
169
+
170
+ /** Fixing the answer clears the refusal — it described the old one. */
171
+ it('lets go of the refusal as soon as the connection is edited', async () => {
172
+ await renderScreen();
173
+ api.testConnection.mockResolvedValue({ ok: false, error: 'The host rejected those.' });
174
+ await userEvent.type(screen.getByLabelText('Repository address'), 'https://x/y.git');
175
+ await userEvent.click(screen.getByRole('button', { name: 'Test connection' }));
176
+ await waitFor(() =>
177
+ expect(screen.getByRole('button', { name: 'Save and continue' })).toBeDisabled(),
178
+ );
179
+
180
+ await userEvent.type(screen.getByLabelText('Access token'), 'ghp_corrected');
181
+ expect(screen.getByRole('button', { name: 'Save and continue' })).toBeEnabled();
182
+ });
183
+
184
+ /**
185
+ * A test result describes the values it was asked about. Editing the address
186
+ * while the request is in flight means the answer that comes back is about
187
+ * values no longer on screen — it must not stand as evidence about the new
188
+ * ones, in either direction.
189
+ */
190
+ it('drops a test result that arrives after the connection was edited', async () => {
191
+ await renderScreen();
192
+ let answer!: (v: unknown) => void;
193
+ api.testConnection.mockReturnValue(new Promise((r) => (answer = r)));
194
+ await userEvent.type(screen.getByLabelText('Repository address'), 'https://x/old.git');
195
+ await userEvent.click(screen.getByRole('button', { name: 'Test connection' }));
196
+ // The answer now in flight is about old.git; this edit supersedes it.
197
+ await userEvent.type(screen.getByLabelText('Repository address'), '2');
198
+ answer({ ok: true, branches: ['main'] });
199
+
200
+ await waitFor(() =>
201
+ expect(screen.getByRole('button', { name: 'Test connection' })).toBeEnabled(),
202
+ );
203
+ expect(screen.queryByText(/Connected/)).toBeNull();
204
+ // Nor do the old answer's branch suggestions fill the version fields.
205
+ expect(screen.getByLabelText('Main branch')).toHaveValue('');
206
+ });
207
+
208
+ /** A stale FAILURE is as misleading as a stale success, and goes the same way. */
209
+ it('drops a test failure that arrives after the connection was edited', async () => {
210
+ await renderScreen();
211
+ let fail!: (e: Error) => void;
212
+ api.testConnection.mockReturnValue(new Promise((_resolve, reject) => (fail = reject)));
213
+ await userEvent.type(screen.getByLabelText('Repository address'), 'https://x/old.git');
214
+ await userEvent.click(screen.getByRole('button', { name: 'Test connection' }));
215
+ // The failure now in flight is about old.git; this edit supersedes it.
216
+ await userEvent.type(screen.getByLabelText('Repository address'), '2');
217
+ fail(new Error('The host rejected those credentials.'));
218
+
219
+ await waitFor(() =>
220
+ expect(screen.getByRole('button', { name: 'Test connection' })).toBeEnabled(),
221
+ );
222
+ expect(screen.queryByText(/rejected those credentials/)).toBeNull();
223
+ });
224
+
225
+ /** A branch name typed while the test runs is an answer, not a blank to fill. */
226
+ it('does not overwrite a branch name typed while the test runs', async () => {
227
+ await renderScreen();
228
+ let answer!: (v: unknown) => void;
229
+ api.testConnection.mockReturnValue(new Promise((r) => (answer = r)));
230
+ await userEvent.type(screen.getByLabelText('Repository address'), 'https://x/y.git');
231
+ await userEvent.click(screen.getByRole('button', { name: 'Test connection' }));
232
+ await userEvent.click(screen.getByText('Advanced'));
233
+ await userEvent.type(screen.getByLabelText('Main branch'), 'release');
234
+ answer({ ok: true, defaultBranch: 'main', branches: ['main', 'release'] });
235
+
236
+ expect(await screen.findByText(/Connected/)).toBeInTheDocument();
237
+ expect(screen.getByLabelText('Main branch')).toHaveValue('release');
238
+ // The field nobody answered still gets the suggestion.
239
+ expect(screen.getByLabelText('Branches that need approval')).toHaveValue('main');
240
+ });
241
+
242
+ /**
243
+ * The button is not the only way in. Pressing Save without ever pressing
244
+ * Test used to store whatever was typed and open the gate on it, so the
245
+ * first news of a wrong token was a broken app — the connection is proven
246
+ * here instead, before anything is written.
247
+ */
248
+ it('proves the connection on a save that never pressed Test', async () => {
249
+ await renderScreen();
250
+ api.testConnection.mockResolvedValue({
251
+ ok: false,
252
+ error: 'No repository at that URL — or the token cannot see it.',
253
+ });
254
+ await userEvent.type(screen.getByLabelText('Repository address'), 'https://x/typo.git');
255
+ await userEvent.type(screen.getByLabelText('Access token'), 'ghp_x');
256
+ await userEvent.click(screen.getByRole('button', { name: 'Save and continue' }));
257
+
258
+ await waitFor(() => expect(api.testConnection).toHaveBeenCalled());
259
+ expect(await screen.findByRole('alert')).toHaveTextContent(/Not saved/);
260
+ expect(api.saveSettings).not.toHaveBeenCalled();
261
+ expect(reload).not.toHaveBeenCalled();
262
+ // And the host's own words are on screen, not just the refusal.
263
+ expect(screen.getByText(/No repository at that URL/)).toBeInTheDocument();
264
+ });
265
+
266
+ /**
267
+ * A test that could not be RUN is not evidence against the credentials.
268
+ * Treating an unreachable test endpoint as a rejection would lock an admin
269
+ * out of the only screen that fixes it.
270
+ */
271
+ it('does not refuse over a test it could not run', async () => {
272
+ await renderScreen();
273
+ api.testConnection.mockRejectedValue(new Error('offline'));
274
+ api.saveSettings.mockResolvedValue({ restartRequired: false, complete: true, settings: SETTINGS });
275
+
276
+ await userEvent.type(screen.getByLabelText('Repository address'), 'https://x/y.git');
277
+ await userEvent.type(screen.getByLabelText('Access token'), 'ghp_x');
278
+ await userEvent.click(screen.getByRole('button', { name: 'Save and continue' }));
279
+
280
+ await waitFor(() => expect(api.saveSettings).toHaveBeenCalled());
281
+ });
282
+
283
+ /**
284
+ * On the Deployment page the app is already running, and single sign-on has
285
+ * nothing to do with whether a repository answers. Refusing an SSO edit over
286
+ * a token that expired somewhere else would be a page that cannot be used to
287
+ * fix anything.
288
+ */
289
+ it('settings mode: an unrelated edit is not held hostage by the connection', async () => {
290
+ const stored = SETTINGS.map((s) =>
291
+ s.key === 'kbRepoUrl'
292
+ ? { ...s, source: 'stored' as const, value: 'https://example.com/kb.git', configured: true }
293
+ : s,
294
+ );
295
+ render(<SetupScreen settings={stored} onSaved={vi.fn()} variant="settings" />);
296
+ api.testConnection.mockResolvedValue({ ok: false, error: 'The host rejected those.' });
297
+ api.saveSettings.mockResolvedValue({ restartRequired: false, complete: true, settings: stored });
298
+
299
+ await userEvent.click(screen.getByRole('button', { name: 'Test connection' }));
300
+ await screen.findByText(/host rejected those/);
301
+
302
+ await userEvent.type(screen.getByLabelText('Application secret'), 'new-secret');
303
+ expect(screen.getByRole('button', { name: 'Save and continue' })).toBeEnabled();
304
+ await userEvent.click(screen.getByRole('button', { name: 'Save and continue' }));
305
+ await waitFor(() => expect(api.saveSettings).toHaveBeenCalled());
306
+ });
307
+
308
+ /** Changing the connection itself is another matter: that has to prove out. */
309
+ it('settings mode: refuses to store a connection the host turned down', async () => {
310
+ render(<SetupScreen settings={SETTINGS} onSaved={vi.fn()} variant="settings" />);
311
+ api.testConnection.mockResolvedValue({ ok: false, error: 'The host rejected those.' });
312
+
313
+ await userEvent.type(screen.getByLabelText('Repository address'), 'https://x/moved.git');
314
+ await userEvent.click(screen.getByRole('button', { name: 'Test connection' }));
315
+ await screen.findByText(/host rejected those/);
316
+
317
+ expect(screen.getByRole('button', { name: 'Save and continue' })).toBeDisabled();
318
+ expect(api.saveSettings).not.toHaveBeenCalled();
319
+ });
320
+
321
+ /**
322
+ * What gates a settings save is whether the CONNECTION would change, not
323
+ * whether a connection field was ever touched. Typing into the address and
324
+ * putting the stored value back changes nothing — the save must not be held
325
+ * behind a repository test for an edit that no longer exists.
326
+ */
327
+ it('settings mode: a field restored to its stored value does not gate the save', async () => {
328
+ const stored = SETTINGS.map((s) =>
329
+ s.key === 'kbRepoUrl'
330
+ ? { ...s, source: 'stored' as const, value: 'https://example.com/kb.git', configured: true }
331
+ : s.key === 'defaultBranch' || s.key === 'protectedBranches'
332
+ ? { ...s, source: 'stored' as const, value: 'main', configured: true }
333
+ : s,
334
+ );
335
+ render(<SetupScreen settings={stored} onSaved={vi.fn()} variant="settings" />);
336
+ api.saveSettings.mockResolvedValue({ restartRequired: false, complete: true, settings: stored });
337
+
338
+ const url = screen.getByLabelText('Repository address');
339
+ await userEvent.type(url, 'X');
340
+ await userEvent.type(url, '{backspace}');
341
+ await userEvent.click(screen.getByRole('button', { name: 'Save and continue' }));
342
+
343
+ await waitFor(() => expect(api.saveSettings).toHaveBeenCalled());
344
+ expect(api.testConnection).not.toHaveBeenCalled();
345
+ });
346
+
144
347
  /** An empty repository is a supported starting point, not a failure. */
145
348
  it('treats an empty repository as a success', async () => {
146
349
  await renderScreen();
@@ -92,6 +92,17 @@ const FIELDS: Record<
92
92
  */
93
93
  const REQUIRED_KEYS = ['kbRepoUrl', 'gitToken', 'defaultBranch', 'protectedBranches'];
94
94
 
95
+ /**
96
+ * The answers a connection test actually proves — the address, the credential
97
+ * and the name that goes beside it.
98
+ *
99
+ * Editing one invalidates the result on screen, because it described the old
100
+ * ones. Editing anything ELSE leaves it standing: whether a repository is
101
+ * reachable has nothing to do with an identity provider's scopes, and clearing
102
+ * it there would ask an admin to prove the same repository twice.
103
+ */
104
+ const CONNECTION_KEYS = ['kbRepoUrl', 'gitToken', 'gitUsername'];
105
+
95
106
  /** The blocks, in the order they are worked through. */
96
107
  const SECTIONS: { id: SettingStatus['section']; title: string; blurb: string }[] = [
97
108
  {
@@ -152,14 +163,71 @@ export function SetupScreen({ settings, onSaved, variant = 'setup' }: Props) {
152
163
  /** Answered, yet this process is still running on the old branch model. */
153
164
  const [needsRestart, setNeedsRestart] = useState(false);
154
165
  const noticeRef = useRef<HTMLDivElement>(null);
166
+ /**
167
+ * Which set of connection answers the screen is showing, bumped on every
168
+ * edit to one of them. A test result describes the answers as they were when
169
+ * the request left; if they changed while it was in flight, the result that
170
+ * comes back is evidence about values no longer on screen and must not be
171
+ * shown as if it were about the new ones.
172
+ */
173
+ const connectionEpoch = useRef(0);
174
+
175
+ /**
176
+ * What a field would save as, given a set of typed answers: what is in them,
177
+ * else what is already stored. Taken over a payload rather than the draft
178
+ * alone so a submit can ask about values it has just derived, which `draft`
179
+ * will not hold until the next render.
180
+ */
181
+ const resolvedIn = (typed: Record<string, string>, key: string) =>
182
+ (typed[key] ?? settings.find((s) => s.key === key)?.value ?? '').trim();
155
183
 
156
184
  /** What a field would save as: what was typed, else what is already stored. */
157
- const resolved = (key: string) =>
158
- (draft[key] ?? settings.find((s) => s.key === key)?.value ?? '').trim();
185
+ const resolved = (key: string) => resolvedIn(draft, key);
159
186
 
160
187
  const editable = settings.filter((s) => s.source !== 'env');
161
188
  const fromEnv = settings.filter((s) => s.source === 'env');
162
189
 
190
+ /**
191
+ * Whether saving now would actually change this connection field: something
192
+ * non-blank was typed, and it is not the stored value typed back in. Secrets
193
+ * have no stored value to show, so any non-blank entry counts as a change —
194
+ * which is right, because it replaces the stored one.
195
+ */
196
+ const connectionKeyChanged = (key: string) => {
197
+ const typed = draft[key]?.trim();
198
+ if (!typed) return false;
199
+ return typed !== (settings.find((s) => s.key === key)?.value ?? '').trim();
200
+ };
201
+
202
+ /**
203
+ * Whether THIS save has to stand behind the repository connection.
204
+ *
205
+ * On first run it always does: everything behind the gate reads from a
206
+ * repository that has to be reachable, and the save that finishes setup is
207
+ * what opens that gate. On the Deployment page only a save that CHANGES the
208
+ * connection does — an admin editing single sign-on has no repository to
209
+ * re-prove, and refusing them over a token that expired somewhere else helps
210
+ * nobody.
211
+ *
212
+ * "Changes" means the value the save would store differs from the stored
213
+ * one — a field someone touched and then restored changes nothing, and a
214
+ * blank field means "leave it alone", not "clear it". Judging by "was it
215
+ * typed in" held saves hostage to edits that no longer exist.
216
+ *
217
+ * There is nothing to prove until there is an address to prove it against; a
218
+ * blank form is the server's to complain about, field by field.
219
+ */
220
+ const mustProveConnection =
221
+ !!resolved('kbRepoUrl') &&
222
+ (variant === 'setup' || CONNECTION_KEYS.some((key) => connectionKeyChanged(key)));
223
+
224
+ /**
225
+ * The host was asked about the answers currently on screen, and said no.
226
+ * Editing any of them clears the result, so this is never about a value the
227
+ * reader has already changed.
228
+ */
229
+ const connectionRejected = mustProveConnection && test?.ok === false;
230
+
163
231
  function set(key: string, value: string) {
164
232
  setDraft((d) => {
165
233
  const next = { ...d, [key]: value };
@@ -181,89 +249,165 @@ export function SetupScreen({ settings, onSaved, variant = 'setup' }: Props) {
181
249
  delete next[key];
182
250
  return next;
183
251
  });
184
- setTest(null);
252
+ if (CONNECTION_KEYS.includes(key)) {
253
+ // Any in-flight test is now asking about values that are gone; the epoch
254
+ // bump makes its answer land as stale rather than as evidence.
255
+ connectionEpoch.current++;
256
+ setTest(null);
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Which branch the repository just named, or the best conventional stand-in.
262
+ *
263
+ * Prefer what the remote calls its trunk. Not every host advertises it —
264
+ * older servers answer `ls-remote` without the symref line — so fall back to
265
+ * the conventional names before the first branch it did list. Leaving these
266
+ * blank is the one way a save can succeed and still not finish setup, which
267
+ * is worth a guess the reader can see and correct.
268
+ */
269
+ function suggestedBranch(result: ConnectionTest): string | null {
270
+ return (
271
+ result.defaultBranch ||
272
+ ['main', 'master', 'trunk'].find((name) => result.branches?.includes(name)) ||
273
+ result.branches?.[0] ||
274
+ // An EMPTY repository has no branch to report, but it will be seeded
275
+ // with whatever is configured here, so the conventional name is the
276
+ // right suggestion. Suggesting nothing was the one way "Connected"
277
+ // could still end, silently, in a save that did not finish setup.
278
+ (result.empty ? 'main' : null)
279
+ );
280
+ }
281
+
282
+ /**
283
+ * Ask the remote, record what it said, and fill the version fields in from
284
+ * it. The repository has just said what it calls its trunk and which
285
+ * branches it has; filling those in beats asking someone to remember, and
286
+ * beats the silent failure of a name that is one character off. Only into
287
+ * fields nobody has answered — never over a name somebody typed.
288
+ *
289
+ * ONE function for both callers — the Test button, and a Save that has to
290
+ * prove the connection before storing it — because two copies of "which
291
+ * branch did it name?" is how the two answers drift apart. It returns what
292
+ * it derived as well as the result, so a submit can use both without waiting
293
+ * for a re-render.
294
+ */
295
+ async function probeConnection(): Promise<{
296
+ result: ConnectionTest;
297
+ derived: Record<string, string>;
298
+ }> {
299
+ const epoch = connectionEpoch.current;
300
+ const result = await testConnection(draft);
301
+ // Read the answer BEFORE storing it, so a response that is not one at all
302
+ // throws to the caller (which treats that as "could not ask") instead of
303
+ // parking a value in state that every reader downstream has to defend
304
+ // against.
305
+ const suggested = result.ok ? suggestedBranch(result) : null;
306
+ // The result describes the connection values captured above. If they were
307
+ // edited while the request was in flight, showing it would let the OLD
308
+ // values' success (or failure) stand in for the new ones — so it is
309
+ // returned to the caller, whose payload is the same snapshot, but never
310
+ // shown. `derived` is likewise computed against that snapshot, because it
311
+ // travels with the payload.
312
+ const stale = epoch !== connectionEpoch.current;
313
+ if (!stale) setTest(result);
314
+ const derived: Record<string, string> = {};
315
+ if (suggested) {
316
+ if (!resolved('defaultBranch')) derived.defaultBranch = suggested;
317
+ if (!resolved('protectedBranches')) derived.protectedBranches = suggested;
318
+ }
319
+ if (!stale && suggested) {
320
+ // Re-check against the LATEST draft, not the snapshot: a branch name
321
+ // typed while the request was in flight is an answer, and a suggestion
322
+ // must never overwrite an answer.
323
+ setDraft((d) => {
324
+ const next = { ...d };
325
+ if (!resolvedIn(d, 'defaultBranch')) next.defaultBranch = suggested;
326
+ if (!resolvedIn(d, 'protectedBranches')) next.protectedBranches = suggested;
327
+ return next;
328
+ });
329
+ }
330
+ return { result, derived };
185
331
  }
186
332
 
187
333
  async function runTest() {
188
334
  setTesting(true);
189
335
  setError(null);
336
+ const epoch = connectionEpoch.current;
190
337
  try {
191
- const result = await testConnection(draft);
192
- setTest(result);
193
- // The repository has just said what it calls its trunk and which
194
- // branches it has. Filling those in beats asking someone to remember —
195
- // and beats the silent failure of a name that is one character off.
196
- // Only into fields nobody has typed in.
197
- // Prefer what the remote calls its trunk. Not every host advertises it —
198
- // older servers answer `ls-remote` without the symref line — so fall back
199
- // to the conventional names before the first branch it did list. Leaving
200
- // these blank is the one way a save can succeed and still not finish
201
- // setup, which is worth a guess the reader can see and correct.
202
- const suggested =
203
- result.defaultBranch ||
204
- ['main', 'master', 'trunk'].find((name) => result.branches?.includes(name)) ||
205
- result.branches?.[0] ||
206
- // An EMPTY repository has no branch to report, but it will be seeded
207
- // with whatever is configured here, so the conventional name is the
208
- // right suggestion. Suggesting nothing was the one way "Connected"
209
- // could still end, silently, in a save that did not finish setup.
210
- (result.empty ? 'main' : null);
211
- if (result.ok && suggested) {
212
- setDraft((d) => ({
213
- ...d,
214
- defaultBranch: d.defaultBranch || suggested,
215
- protectedBranches: d.protectedBranches || suggested,
216
- }));
217
- }
338
+ await probeConnection();
218
339
  } catch (err) {
219
- setError(err instanceof Error ? err.message : 'Could not test the connection.');
340
+ // A FAILURE goes stale the same way a success does: if the connection
341
+ // was edited while this request was out, the error describes values no
342
+ // longer on screen, and showing it would complain about something the
343
+ // reader already changed.
344
+ if (epoch === connectionEpoch.current) {
345
+ setError(err instanceof Error ? err.message : 'Could not test the connection.');
346
+ }
220
347
  } finally {
221
348
  setTesting(false);
222
349
  }
223
350
  }
224
351
 
225
- /**
226
- * Ask the repository which branch to use, for someone who pressed Save
227
- * without pressing Test. They have supplied everything they can be expected
228
- * to know; a branch name is something we can look up, so refusing over it
229
- * asks a question with a knowable answer. Only when the lookup ALSO comes
230
- * back empty is the message worth showing.
231
- */
232
- async function deriveVersions(): Promise<Record<string, string> | null> {
233
- try {
234
- const result = await testConnection(draft);
235
- if (!result.ok) return null;
236
- const suggested =
237
- result.defaultBranch ||
238
- ['main', 'master', 'trunk'].find((name) => result.branches?.includes(name)) ||
239
- result.branches?.[0] ||
240
- // Same empty-repository rule as the visible test button above.
241
- (result.empty ? 'main' : undefined);
242
- if (!suggested) return null;
243
- setTest(result);
244
- const derived: Record<string, string> = {};
245
- if (!resolved('defaultBranch')) derived.defaultBranch = suggested;
246
- if (!resolved('protectedBranches')) derived.protectedBranches = suggested;
247
- setDraft((d) => ({ ...d, ...derived }));
248
- return derived;
249
- } catch {
250
- // The save carries on and the server says what is missing — a failed
251
- // lookup is not itself an error the reader can act on.
252
- return null;
253
- }
254
- }
255
-
256
352
  async function submit(e: FormEvent) {
257
353
  e.preventDefault();
258
354
  if (saving) return;
259
355
  setSaving(true);
260
356
  setError(null);
261
357
  setProblems({});
358
+ // The list describes what the LAST completed save left unanswered. A new
359
+ // attempt supersedes it — leaving it up put "Saved what you filled in, but
360
+ // this deployment still needs…" directly above this attempt's "Not saved."
361
+ setStillMissing([]);
262
362
  try {
263
363
  let payload = draft;
264
- if (!resolved('defaultBranch') || !resolved('protectedBranches')) {
265
- const derived = await deriveVersions();
266
- if (derived) payload = { ...draft, ...derived };
364
+ /** What the host said this time, or null when it could not be asked. */
365
+ let proven: ConnectionTest | null = test;
366
+ let probed = false;
367
+ const probe = async () => {
368
+ probed = true;
369
+ try {
370
+ const { result, derived } = await probeConnection();
371
+ proven = result;
372
+ payload = { ...payload, ...derived };
373
+ } catch {
374
+ // The lookup itself failed — the endpoint is down, the request threw.
375
+ // That is not evidence about the credentials, so nothing is concluded
376
+ // from it and the save carries on: the server has the last word, and
377
+ // a failed lookup is not an error the reader can act on.
378
+ proven = null;
379
+ }
380
+ };
381
+
382
+ if (mustProveConnection && !test?.ok) {
383
+ // PROVE THE CONNECTION BEFORE STORING IT. The server's completeness
384
+ // check asks only whether the answers are PRESENT — so a token the
385
+ // host rejects finishes setup just as well as one it accepts, and the
386
+ // gate opens onto an app whose every call fails against a repository
387
+ // it cannot clone. This is the one moment that can tell the two apart.
388
+ setTesting(true);
389
+ await probe();
390
+ setTesting(false);
391
+ if (proven && !proven.ok) {
392
+ setError(
393
+ variant === 'setup'
394
+ ? 'Not saved. Nothing behind this screen works until the repository answers, and it did not — fix the connection above and test it again.'
395
+ : 'Not saved. The repository did not answer with those details — fix the connection above and test it again.',
396
+ );
397
+ return;
398
+ }
399
+ }
400
+
401
+ // Someone who pressed Save without pressing Test has supplied everything
402
+ // they can be expected to know; a branch name is something we can look
403
+ // up, so refusing over it asks a question with a knowable answer. Only
404
+ // when the remote has not already been asked this time round — the probe
405
+ // above fills the same fields from the same answer.
406
+ if (
407
+ !probed &&
408
+ (!resolvedIn(payload, 'defaultBranch') || !resolvedIn(payload, 'protectedBranches'))
409
+ ) {
410
+ await probe();
267
411
  }
268
412
  const result = await saveSettings(payload);
269
413
  setRestartRequired(result.restartRequired);
@@ -481,7 +625,10 @@ export function SetupScreen({ settings, onSaved, variant = 'setup' }: Props) {
481
625
  variant="outline"
482
626
  size="sm"
483
627
  onClick={() => void runTest()}
484
- disabled={testing}
628
+ // Also while SAVING: a save may be asking the remote
629
+ // itself, and a second test racing it would overwrite
630
+ // both the result and the versions derived from it.
631
+ disabled={testing || saving}
485
632
  >
486
633
  {testing ? 'Checking…' : 'Test connection'}
487
634
  </Button>
@@ -542,10 +689,30 @@ export function SetupScreen({ settings, onSaved, variant = 'setup' }: Props) {
542
689
  })}
543
690
 
544
691
 
545
- <div className="flex items-center gap-3">
546
- <Button type="submit" variant="primary" disabled={saving}>
692
+ {/* A rejected connection stops here rather than at the far side of
693
+ it. Saving these answers would finish setup — the server checks
694
+ that they are present, not that they work — and open the app onto
695
+ a repository it cannot reach, which reads as a broken product
696
+ rather than a wrong token. */}
697
+ <div className="flex flex-wrap items-center gap-3">
698
+ <Button
699
+ type="submit"
700
+ variant="primary"
701
+ disabled={saving || testing || connectionRejected}
702
+ // Described by the refusal, so a reader who lands on a button
703
+ // that will not move is told why rather than left guessing.
704
+ aria-describedby={connectionRejected ? 'connection-refusal' : undefined}
705
+ >
547
706
  {saving ? 'Saving…' : 'Save and continue'}
548
707
  </Button>
708
+ {connectionRejected && (
709
+ // Not a live region: the test panel above already announced the
710
+ // host's own words, and the save banner announces a blocked
711
+ // attempt. This is the label for a button that will not move.
712
+ <span id="connection-refusal" className="text-meta text-danger">
713
+ The repository turned that connection down. Fix it above and test again.
714
+ </span>
715
+ )}
549
716
  </div>
550
717
  </form>
551
718