@bevel-software/platform-core-frontend 0.27.0 → 0.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/package.json +2 -2
  2. package/src/core/ProductName.tsx +4 -4
  3. package/src/core/__tests__/ProductName.test.tsx +46 -0
  4. package/src/core/maker-url.ts +30 -0
  5. package/src/core/registry.ts +27 -0
  6. package/src/lib/__tests__/latest-request.test.ts +48 -0
  7. package/src/lib/latest-request.ts +45 -0
  8. package/src/modules/access/__tests__/ManageAccessDialog.no-sso-invite.test.tsx +222 -0
  9. package/src/modules/access/api.ts +19 -3
  10. package/src/modules/access/components/ManageAccessDialog.tsx +60 -7
  11. package/src/modules/admin/__tests__/AdminRolesPage.fixed-admin.test.tsx +16 -1
  12. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +284 -39
  13. package/src/modules/admin/components/AdminRolesPage.tsx +13 -14
  14. package/src/modules/admin/components/UserAccountsPage.tsx +91 -107
  15. package/src/modules/admin/services/roles.api.ts +14 -1
  16. package/src/modules/auth/__tests__/LoginScreen.test.tsx +80 -5
  17. package/src/modules/auth/__tests__/sso-strict-probe.test.ts +66 -0
  18. package/src/modules/auth/components/LoginScreen.tsx +100 -75
  19. package/src/modules/auth/services/account.api.ts +31 -2
  20. package/src/modules/auth/services/sso.ts +29 -8
  21. package/src/modules/auth/state/use-sign-in-methods.ts +41 -0
  22. package/src/modules/onboarding/__tests__/InviteButton.test.tsx +214 -0
  23. package/src/modules/onboarding/__tests__/first-page-prompt.test.ts +56 -1
  24. package/src/modules/onboarding/__tests__/get-started-column.test.tsx +538 -81
  25. package/src/modules/onboarding/__tests__/invite-dialog.test.tsx +543 -124
  26. package/src/modules/onboarding/__tests__/invite-emails.test.ts +247 -0
  27. package/src/modules/onboarding/components/GetStartedColumn.tsx +30 -11
  28. package/src/modules/onboarding/components/InviteButton.tsx +119 -15
  29. package/src/modules/onboarding/components/InviteDialog.tsx +392 -75
  30. package/src/modules/onboarding/first-page-prompt.ts +34 -0
  31. package/src/modules/onboarding/invite-emails.ts +171 -33
  32. package/src/modules/onboarding/state/invite-dialog.context.ts +7 -4
  33. package/src/modules/onboarding/state/invite-dialog.tsx +12 -4
  34. package/src/modules/toolbar/commands/actions.tsx +10 -4
  35. package/src/modules/toolbar/commands/useCommandActions.ts +5 -3
  36. package/src/modules/toolbar/components/AppSwitcher.tsx +19 -0
  37. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +46 -1
  38. package/src/modules/toolbar/components/__tests__/SearchPalette.test.tsx +34 -2
  39. package/src/modules/workspace/hooks/__tests__/useCreatePage.test.ts +137 -0
  40. package/src/modules/workspace/hooks/__tests__/useKnowledgeWriteTarget.test.ts +302 -0
  41. package/src/modules/workspace/hooks/useCreatePage.ts +118 -28
  42. package/src/modules/workspace/hooks/useKnowledgeWriteTarget.ts +238 -0
@@ -1,6 +1,7 @@
1
1
  import { useState, useEffect, type FormEvent } from 'react';
2
2
  import { useAuth } from '../state/auth.context';
3
3
  import { ProductName } from '../../../core/ProductName';
4
+ import { useAppRegistry } from '../../../core/registry';
4
5
  import {
5
6
  startSsoLogin,
6
7
  fetchLoginProviders,
@@ -24,26 +25,32 @@ const OAUTH_ERROR_MESSAGES: Record<string, string> = {
24
25
  'Your sign-in provider has not verified your email address, so it cannot be used to sign in here.',
25
26
  };
26
27
 
28
+ /** The message for an error an SSO callback left for this screen (stored by useAuthState), if any. */
29
+ function storedOAuthError(): string | null {
30
+ const code = sessionStorage.getItem(OAUTH_ERROR_KEY);
31
+ return code ? (OAUTH_ERROR_MESSAGES[code] ?? 'Sign-in failed.') : null;
32
+ }
33
+
27
34
  export function LoginScreen() {
28
35
  const { login } = useAuth();
36
+ const { loginLinks } = useAppRegistry();
29
37
  const [email, setEmail] = useState('');
30
38
  const [password, setPassword] = useState('');
31
- const [error, setError] = useState<string | null>(null);
39
+ // An SSO callback's error is the screen's first message, read as the state
40
+ // is made so it shows on the first render. StrictMode runs this twice,
41
+ // which is why the stored error is cleared in the effect, not here.
42
+ const [error, setError] = useState<string | null>(storedOAuthError);
32
43
  const [submitting, setSubmitting] = useState(false);
33
44
  // Default to password-only until the probe resolves, matching fetchLoginProviders'
34
45
  // failure fallback so we never flash a button the backend can't service.
35
46
  const [passwordEnabled, setPasswordEnabled] = useState(true);
36
47
  const [ssoProviders, setSsoProviders] = useState<SsoProvider[]>([]);
37
48
 
38
- // Surface an error returned by an SSO callback (stored by useAuthState),
39
- // and probe which login methods this deployment offers.
49
+ // Clear the SSO callback's error once shown, so it is not shown again on a
50
+ // later visit, and probe which login methods this deployment offers.
40
51
  useEffect(() => {
41
52
  let mounted = true;
42
- const oauthError = sessionStorage.getItem(OAUTH_ERROR_KEY);
43
- if (oauthError) {
44
- sessionStorage.removeItem(OAUTH_ERROR_KEY);
45
- setError(OAUTH_ERROR_MESSAGES[oauthError] ?? 'Sign-in failed.');
46
- }
53
+ sessionStorage.removeItem(OAUTH_ERROR_KEY);
47
54
  // Capability probe: never set state after unmount.
48
55
  fetchLoginProviders()
49
56
  .then((providers) => {
@@ -70,81 +77,99 @@ export function LoginScreen() {
70
77
  }
71
78
  }
72
79
 
80
+ // The page scrolls rather than the root (which never does): on a screen too
81
+ // short for the card and its links, both stay reachable. The inner column is
82
+ // at least the page's height, so a card that fits is still centred.
73
83
  return (
74
- <div className="flex items-center justify-center h-full bg-white">
75
- <form
76
- onSubmit={handleSubmit}
77
- className="bg-white p-8 rounded-xl border border-line w-full max-w-sm space-y-5"
78
- >
79
- <div className="text-center space-y-1">
80
- <h1 className="text-2xl font-semibold text-ink">
81
- <ProductName />
82
- </h1>
83
- <p className="text-sm text-ink-muted">Sign in to continue</p>
84
- </div>
84
+ <div className="h-full overflow-y-auto bg-white">
85
+ <div className="flex flex-col items-center justify-center gap-4 min-h-full p-4">
86
+ <form
87
+ onSubmit={handleSubmit}
88
+ className="bg-white p-8 rounded-xl border border-line w-full max-w-sm space-y-5"
89
+ >
90
+ <div className="text-center space-y-1">
91
+ <h1 className="text-2xl font-semibold text-ink">
92
+ <ProductName />
93
+ </h1>
94
+ <p className="text-sm text-ink-muted">Sign in to continue</p>
95
+ </div>
96
+
97
+ {passwordEnabled && (
98
+ <>
99
+ <div className="space-y-3">
100
+ <label className="block space-y-1">
101
+ <span className="text-xs text-ink-muted">Email</span>
102
+ <input
103
+ type="email"
104
+ required
105
+ autoComplete="email"
106
+ value={email}
107
+ onChange={(e) => setEmail(e.target.value)}
108
+ className="w-full rounded-md bg-sunken border border-line-strong px-3 py-2 text-sm text-ink focus:outline-none focus:border-accent"
109
+ />
110
+ </label>
111
+ <label className="block space-y-1">
112
+ <span className="text-xs text-ink-muted">Password</span>
113
+ <input
114
+ type="password"
115
+ required
116
+ autoComplete="current-password"
117
+ value={password}
118
+ onChange={(e) => setPassword(e.target.value)}
119
+ className="w-full rounded-md bg-sunken border border-line-strong px-3 py-2 text-sm text-ink focus:outline-none focus:border-accent"
120
+ />
121
+ </label>
122
+ </div>
123
+
124
+ <button
125
+ type="submit"
126
+ disabled={submitting}
127
+ className="w-full rounded-md bg-accent text-white text-sm font-medium py-2 hover:bg-accent-hover disabled:opacity-60 disabled:cursor-not-allowed"
128
+ >
129
+ {submitting ? 'Signing in…' : 'Sign in'}
130
+ </button>
131
+ </>
132
+ )}
133
+
134
+ {error && (
135
+ <div className="text-sm text-red-600" role="alert">
136
+ {error}
137
+ </div>
138
+ )}
85
139
 
86
- {passwordEnabled && (
87
- <>
88
- <div className="space-y-3">
89
- <label className="block space-y-1">
90
- <span className="text-xs text-ink-muted">Email</span>
91
- <input
92
- type="email"
93
- required
94
- autoComplete="email"
95
- value={email}
96
- onChange={(e) => setEmail(e.target.value)}
97
- className="w-full rounded-md bg-sunken border border-line-strong px-3 py-2 text-sm text-ink focus:outline-none focus:border-accent"
98
- />
99
- </label>
100
- <label className="block space-y-1">
101
- <span className="text-xs text-ink-muted">Password</span>
102
- <input
103
- type="password"
104
- required
105
- autoComplete="current-password"
106
- value={password}
107
- onChange={(e) => setPassword(e.target.value)}
108
- className="w-full rounded-md bg-sunken border border-line-strong px-3 py-2 text-sm text-ink focus:outline-none focus:border-accent"
109
- />
110
- </label>
140
+ {passwordEnabled && ssoProviders.length > 0 && (
141
+ <div className="flex items-center gap-3 text-xs text-ink-faint">
142
+ <span className="h-px flex-1 bg-line" />
143
+ or
144
+ <span className="h-px flex-1 bg-line" />
111
145
  </div>
146
+ )}
112
147
 
148
+ {ssoProviders.map((provider) => (
113
149
  <button
114
- type="submit"
115
- disabled={submitting}
116
- className="w-full rounded-md bg-accent text-white text-sm font-medium py-2 hover:bg-accent-hover disabled:opacity-60 disabled:cursor-not-allowed"
150
+ key={provider.key}
151
+ type="button"
152
+ onClick={() => startSsoLogin(provider)}
153
+ className="w-full rounded-md border border-line-strong bg-white text-ink text-sm font-medium py-2 hover:bg-hover"
117
154
  >
118
- {submitting ? 'Signing in…' : 'Sign in'}
155
+ {provider.label}
119
156
  </button>
120
- </>
157
+ ))}
158
+ </form>
159
+ {loginLinks && loginLinks.length > 0 && (
160
+ <nav aria-label="Legal">
161
+ <ul className="flex flex-wrap justify-center gap-x-4 gap-y-1 text-xs text-ink-muted">
162
+ {loginLinks.map((link) => (
163
+ <li key={link.href}>
164
+ <a href={link.href} className="hover:underline">
165
+ {link.label}
166
+ </a>
167
+ </li>
168
+ ))}
169
+ </ul>
170
+ </nav>
121
171
  )}
122
-
123
- {error && (
124
- <div className="text-sm text-red-600" role="alert">
125
- {error}
126
- </div>
127
- )}
128
-
129
- {passwordEnabled && ssoProviders.length > 0 && (
130
- <div className="flex items-center gap-3 text-xs text-ink-faint">
131
- <span className="h-px flex-1 bg-line" />
132
- or
133
- <span className="h-px flex-1 bg-line" />
134
- </div>
135
- )}
136
-
137
- {ssoProviders.map((provider) => (
138
- <button
139
- key={provider.key}
140
- type="button"
141
- onClick={() => startSsoLogin(provider)}
142
- className="w-full rounded-md border border-line-strong bg-white text-ink text-sm font-medium py-2 hover:bg-hover"
143
- >
144
- {provider.label}
145
- </button>
146
- ))}
147
- </form>
172
+ </div>
148
173
  </div>
149
174
  );
150
175
  }
@@ -12,6 +12,10 @@ export interface AccountSummary {
12
12
  * in with the environment password whether or not a hash is stored.
13
13
  */
14
14
  isEnvAdmin: boolean;
15
+ /** One of the deployment's owners (`ADMIN_EMAIL`): never switched off, and its password is not set here. */
16
+ isOwner: boolean;
17
+ /** An owner who can sign back in with the server's password, so their account may be deleted; false otherwise. */
18
+ ownerCanBeDeleted: boolean;
15
19
  /** When an admin switched the account off; null while it is on. */
16
20
  deactivatedAt: string | null;
17
21
  /** One of the accounts the platform runs its own work as: it is never switched off. */
@@ -69,6 +73,11 @@ export async function listAccounts(): Promise<AccountSummary[]> {
69
73
  * upsert). Without a password the account is for single sign-on: the person
70
74
  * finds it waiting the first time they sign in.
71
75
  *
76
+ * With `keepExistingPassword` (an invite's starting password) the password
77
+ * goes only to a new account or a switched-on one that has none; the reply's
78
+ * `passwordSet` says whether it did, and `deactivated` whether it did not
79
+ * because the account is switched off.
80
+ *
72
81
  * A refusal throws {@link AccountRequestError}; `kind: 'admission'` means
73
82
  * the deployment's admission rules had no place for the account.
74
83
  */
@@ -76,17 +85,37 @@ export async function createAccount(
76
85
  email: string,
77
86
  name: string,
78
87
  password?: string,
79
- ): Promise<void> {
88
+ options: { keepExistingPassword?: boolean } = {},
89
+ ): Promise<{ passwordSet?: boolean; deactivated?: boolean; notified?: string[] }> {
80
90
  const res = await authFetch('/api/admin/accounts', {
81
91
  method: 'POST',
82
92
  headers: { 'Content-Type': 'application/json' },
83
- body: JSON.stringify({ email, name: name || undefined, password: password || undefined }),
93
+ body: JSON.stringify({
94
+ email,
95
+ name: name || undefined,
96
+ password: password || undefined,
97
+ keepExistingPassword: options.keepExistingPassword || undefined,
98
+ }),
84
99
  });
85
100
  if (!res.ok) {
86
101
  const body = (await res.json().catch(() => ({}))) as { error?: unknown; kind?: unknown };
87
102
  const message = typeof body.error === 'string' && body.error ? body.error : 'Could not create account';
88
103
  throw new AccountRequestError(message, res.status, typeof body.kind === 'string' ? body.kind : null);
89
104
  }
105
+ const body = (await res.json().catch(() => ({}))) as {
106
+ passwordSet?: unknown;
107
+ deactivated?: unknown;
108
+ notified?: unknown;
109
+ };
110
+ // `notified`: how the deployment told a NEW account's person of the invite
111
+ // (`'email'`, say), as its listeners answered; empty or absent when nobody
112
+ // did and the admin hands over the link themselves.
113
+ const notified = Array.isArray(body.notified) ? body.notified.filter((c): c is string => typeof c === 'string') : [];
114
+ return {
115
+ ...(typeof body.passwordSet === 'boolean' ? { passwordSet: body.passwordSet } : {}),
116
+ ...(body.deactivated === true ? { deactivated: true } : {}),
117
+ ...(notified.length > 0 ? { notified } : {}),
118
+ };
90
119
  }
91
120
 
92
121
  /**
@@ -82,22 +82,43 @@ export function takePostLoginRedirect(): string | null {
82
82
  /**
83
83
  * Probe which login methods are enabled. On failure default to password-only
84
84
  * so a transient error never hides the only working method (and never
85
- * surfaces an SSO button the backend can't service).
85
+ * surfaces an SSO button the backend can't service). This is the strict probe
86
+ * below with that fallback, not a second reading of the answer.
86
87
  */
87
88
  export async function fetchLoginProviders(): Promise<LoginProviders> {
88
89
  try {
89
- const res = await fetch('/api/auth/providers');
90
- if (!res.ok) return { password: true, sso: [] };
91
- const body = (await res.json()) as Partial<LoginProviders>;
92
- return {
93
- password: body.password !== false,
94
- sso: Array.isArray(body.sso) ? body.sso : [],
95
- };
90
+ return await fetchLoginProvidersStrict();
96
91
  } catch {
97
92
  return { password: true, sso: [] };
98
93
  }
99
94
  }
100
95
 
96
+ /**
97
+ * The one reading of `GET /api/auth/providers`: rejects on a failed request,
98
+ * a non-OK answer or a body that does not carry both answers, instead of
99
+ * guessing. The login screen wants the password-only fallback (see
100
+ * `fetchLoginProviders`); the Invite dialog and Manage access must tell "no
101
+ * single sign-on" from "couldn't check", because they say different things to
102
+ * the admin.
103
+ */
104
+ export async function fetchLoginProvidersStrict(): Promise<LoginProviders> {
105
+ const res = await fetch('/api/auth/providers');
106
+ if (!res.ok) throw new Error(`Couldn't read the sign-in methods (${res.status})`);
107
+ const body = (await res.json()) as { password?: unknown; sso?: unknown } | null;
108
+ const sso = body?.sso;
109
+ if (
110
+ typeof body?.password !== 'boolean' ||
111
+ !Array.isArray(sso) ||
112
+ !sso.every(
113
+ (p: Partial<SsoProvider> | null) =>
114
+ typeof p?.key === 'string' && typeof p.label === 'string' && typeof p.startPath === 'string',
115
+ )
116
+ ) {
117
+ throw new Error("Couldn't read the sign-in methods");
118
+ }
119
+ return { password: body.password, sso: sso as SsoProvider[] };
120
+ }
121
+
101
122
  /**
102
123
  * If the current page is any provider's OAuth callback, extract the
103
124
  * token/error from the fragment and scrub the URL (so the token never lingers
@@ -0,0 +1,41 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import { fetchLoginProvidersStrict, type LoginProviders } from '../services/sso';
3
+
4
+ /**
5
+ * How this deployment signs people in, as far as the caller knows:
6
+ * `loading` until the first answer, `failed` when the check could not be
7
+ * made (never guessed — see `fetchLoginProvidersStrict`), `ready` with the
8
+ * methods. `retry` asks again.
9
+ */
10
+ export type SignInMethodsState =
11
+ | { status: 'loading'; retry(): void }
12
+ | { status: 'failed'; retry(): void }
13
+ | { status: 'ready'; methods: LoginProviders; retry(): void };
14
+
15
+ export function useSignInMethods(): SignInMethodsState {
16
+ const [state, setState] = useState<
17
+ { status: 'loading' } | { status: 'failed' } | { status: 'ready'; methods: LoginProviders }
18
+ >({ status: 'loading' });
19
+ const [attempt, setAttempt] = useState(0);
20
+ const retry = useCallback(() => {
21
+ setState({ status: 'loading' });
22
+ setAttempt((a) => a + 1);
23
+ }, []);
24
+
25
+ useEffect(() => {
26
+ let cancelled = false;
27
+ fetchLoginProvidersStrict().then(
28
+ (methods) => {
29
+ if (!cancelled) setState({ status: 'ready', methods });
30
+ },
31
+ () => {
32
+ if (!cancelled) setState({ status: 'failed' });
33
+ },
34
+ );
35
+ return () => {
36
+ cancelled = true;
37
+ };
38
+ }, [attempt]);
39
+
40
+ return { ...state, retry };
41
+ }
@@ -0,0 +1,214 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { render, screen, waitFor, within } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { AuthContext } from '../../auth/state/auth.context';
5
+ import { authValue } from '../../library/__tests__/auth-harness';
6
+ import { AdminContext, type AdminContextValue } from '../../admin/state/admin.context';
7
+ import type { AdminContact } from '../../access/api';
8
+ import { InviteButton } from '../components/InviteButton';
9
+ import { InviteDialogContext, type InviteDialogController } from '../state/invite-dialog.context';
10
+ import { InviteDialogProvider } from '../state/invite-dialog';
11
+
12
+ /**
13
+ * The top bar's Invite, for everyone signed in: an admin's click opens the
14
+ * Invite dialog; anyone else's opens a popover that says to ask an admin and
15
+ * lists the admins, each with an Email button carrying a prefilled request.
16
+ */
17
+
18
+ const { fetchAdminsMock } = vi.hoisted(() => ({
19
+ fetchAdminsMock: vi.fn<() => Promise<AdminContact[]>>(),
20
+ }));
21
+ vi.mock('../../access/api', async (importOriginal) => ({
22
+ ...(await importOriginal<typeof import('../../access/api')>()),
23
+ fetchAdmins: fetchAdminsMock,
24
+ }));
25
+ vi.mock('../../../lib/api', () => ({ authFetch: vi.fn() }));
26
+ // The dialog asks how people sign in; this file is about the button.
27
+ vi.mock('../../auth/services/sso', async (importOriginal) => ({
28
+ ...(await importOriginal<typeof import('../../auth/services/sso')>()),
29
+ fetchLoginProvidersStrict: vi.fn(async () => ({ password: true, sso: [] })),
30
+ }));
31
+
32
+ const ADMINS: AdminContact[] = [
33
+ { name: 'Dana Admin', email: 'dana@acme.com' },
34
+ { name: 'Sam Ortiz', email: 'sam.ortiz@acme.com' },
35
+ ];
36
+
37
+ function adminValue(isAdmin: boolean, isAdminLoading = false): AdminContextValue {
38
+ return {
39
+ isAdmin,
40
+ isAdminLoading,
41
+ unreadCount: 0,
42
+ lastSeen: null,
43
+ markSeen: () => {},
44
+ refresh: () => {},
45
+ rolesConfigCorrupted: false,
46
+ rolesConfigErrors: [],
47
+ runRolesRecovery: async () => {},
48
+ };
49
+ }
50
+
51
+ /** With a stub controller, so a test can tell whether the dialog was asked for. */
52
+ function mountWithController(isAdmin: boolean, compact = false, isAdminLoading = false) {
53
+ const invite: InviteDialogController = { open: vi.fn(), invitedRevision: 0 };
54
+ render(
55
+ <AuthContext.Provider value={authValue()}>
56
+ <AdminContext.Provider value={adminValue(isAdmin, isAdminLoading)}>
57
+ <InviteDialogContext.Provider value={invite}>
58
+ <div>
59
+ <p>Elsewhere on the page</p>
60
+ <InviteButton compact={compact} />
61
+ </div>
62
+ </InviteDialogContext.Provider>
63
+ </AdminContext.Provider>
64
+ </AuthContext.Provider>,
65
+ );
66
+ return invite;
67
+ }
68
+
69
+ function popover() {
70
+ return screen.queryByRole('group', { name: 'Ask an admin to invite people' });
71
+ }
72
+
73
+ beforeEach(() => {
74
+ fetchAdminsMock.mockReset().mockResolvedValue(ADMINS);
75
+ });
76
+
77
+ describe('InviteButton while the admin check is still out', () => {
78
+ it('is visibly disabled, so a click opens nothing: no ask-an-admin popover for someone who may be an admin', async () => {
79
+ const invite = mountWithController(false, false, true);
80
+ expect(screen.getByRole('button', { name: 'Invite' })).toBeDisabled();
81
+ await userEvent.click(screen.getByRole('button', { name: 'Invite' }));
82
+ expect(popover()).toBeNull();
83
+ expect(fetchAdminsMock).not.toHaveBeenCalled();
84
+ expect(invite.open).not.toHaveBeenCalled();
85
+ });
86
+ });
87
+
88
+ describe('InviteButton for an admin', () => {
89
+ it('opens the Invite dialog, and no popover', async () => {
90
+ render(
91
+ <AuthContext.Provider value={authValue()}>
92
+ <AdminContext.Provider value={adminValue(true)}>
93
+ <InviteDialogProvider>
94
+ <InviteButton />
95
+ </InviteDialogProvider>
96
+ </AdminContext.Provider>
97
+ </AuthContext.Provider>,
98
+ );
99
+ await userEvent.click(screen.getByRole('button', { name: 'Invite' }));
100
+ expect(screen.getByRole('dialog', { name: 'Invite your team' })).toBeInTheDocument();
101
+ expect(popover()).not.toBeInTheDocument();
102
+ expect(fetchAdminsMock).not.toHaveBeenCalled();
103
+ });
104
+
105
+ it('drops its word on a compact toolbar but keeps its name, and still opens the dialog', async () => {
106
+ const invite = mountWithController(true, true);
107
+ const button = screen.getByRole('button', { name: 'Invite' });
108
+ // Exactly empty: the word is the accessible name, never on screen.
109
+ expect(button.textContent).toBe('');
110
+ await userEvent.click(button);
111
+ expect(invite.open).toHaveBeenCalledTimes(1);
112
+ expect(popover()).not.toBeInTheDocument();
113
+ });
114
+ });
115
+
116
+ describe('InviteButton for anyone else', () => {
117
+ it('is shown, and opens a popover saying to ask an admin — not the dialog', async () => {
118
+ const invite = mountWithController(false);
119
+ const button = screen.getByRole('button', { name: 'Invite' });
120
+ expect(button).toHaveAttribute('aria-expanded', 'false');
121
+ await userEvent.click(button);
122
+ expect(button).toHaveAttribute('aria-expanded', 'true');
123
+ const panel = popover()!;
124
+ expect(within(panel).getByText('Ask an admin to invite people')).toBeInTheDocument();
125
+ expect(within(panel).getByText('Only admins can add people to this workspace.')).toBeInTheDocument();
126
+ expect(invite.open).not.toHaveBeenCalled();
127
+ });
128
+
129
+ it('lists every admin with name, email and an Email button carrying the request', async () => {
130
+ mountWithController(false);
131
+ await userEvent.click(screen.getByRole('button', { name: 'Invite' }));
132
+ const list = await screen.findByRole('list', { name: 'Admins' });
133
+ const rows = within(list).getAllByRole('listitem');
134
+ expect(rows).toHaveLength(2);
135
+ expect(within(rows[0]).getByText('Dana Admin')).toBeInTheDocument();
136
+ expect(within(rows[0]).getByText('dana@acme.com')).toBeInTheDocument();
137
+ expect(within(rows[1]).getByText('Sam Ortiz')).toBeInTheDocument();
138
+ expect(within(rows[1]).getByText('sam.ortiz@acme.com')).toBeInTheDocument();
139
+
140
+ const email = within(rows[0]).getByRole('link', { name: 'Email Dana Admin' });
141
+ expect(email).toHaveTextContent('Email');
142
+ const href = email.getAttribute('href')!;
143
+ expect(href.startsWith('mailto:dana@acme.com?')).toBe(true);
144
+ const params = new URLSearchParams(href.slice(href.indexOf('?') + 1));
145
+ expect(params.get('subject')).toBe('Please invite someone to Hexis');
146
+ expect(params.get('body')).toBe(
147
+ `Hi Dana,\n\nCould you invite ... to our workspace at ${window.location.origin}?\n\nThanks`,
148
+ );
149
+ expect(within(rows[1]).getByRole('link', { name: 'Email Sam Ortiz' }).getAttribute('href')).toMatch(
150
+ /^mailto:sam\.ortiz@acme\.com\?.*Hi%20Sam%2C/,
151
+ );
152
+ });
153
+
154
+ it('keeps its two lines and lists nobody when the admins cannot be read', async () => {
155
+ fetchAdminsMock.mockRejectedValue(new Error('down'));
156
+ mountWithController(false);
157
+ await userEvent.click(screen.getByRole('button', { name: 'Invite' }));
158
+ await waitFor(() => expect(fetchAdminsMock).toHaveBeenCalled());
159
+ const panel = popover()!;
160
+ expect(within(panel).getByText('Ask an admin to invite people')).toBeInTheDocument();
161
+ expect(within(panel).getByText('Only admins can add people to this workspace.')).toBeInTheDocument();
162
+ expect(within(panel).queryByRole('list')).not.toBeInTheDocument();
163
+ });
164
+
165
+ it('closes on Escape and hands focus back to the button', async () => {
166
+ mountWithController(false);
167
+ const button = screen.getByRole('button', { name: 'Invite' });
168
+ await userEvent.click(button);
169
+ await screen.findByRole('list', { name: 'Admins' });
170
+ await userEvent.keyboard('{Escape}');
171
+ expect(popover()).not.toBeInTheDocument();
172
+ expect(button).toHaveFocus();
173
+ });
174
+
175
+ it('closes on a click outside', async () => {
176
+ mountWithController(false);
177
+ await userEvent.click(screen.getByRole('button', { name: 'Invite' }));
178
+ expect(popover()).toBeInTheDocument();
179
+ await userEvent.click(screen.getByText('Elsewhere on the page'));
180
+ expect(popover()).not.toBeInTheDocument();
181
+ });
182
+
183
+ it('toggles closed on a second click of the button', async () => {
184
+ mountWithController(false);
185
+ const button = screen.getByRole('button', { name: 'Invite' });
186
+ await userEvent.click(button);
187
+ await userEvent.click(button);
188
+ expect(popover()).not.toBeInTheDocument();
189
+ });
190
+
191
+ it('the compact icon opens the same popover', async () => {
192
+ const invite = mountWithController(false, true);
193
+ await userEvent.click(screen.getByRole('button', { name: 'Invite' }));
194
+ expect(popover()).toBeInTheDocument();
195
+ expect(await screen.findByRole('list', { name: 'Admins' })).toBeInTheDocument();
196
+ expect(invite.open).not.toHaveBeenCalled();
197
+ });
198
+ });
199
+
200
+ describe('InviteButton outside a provider', () => {
201
+ it('renders nothing, for an admin or anyone else', () => {
202
+ render(
203
+ <AuthContext.Provider value={authValue()}>
204
+ <AdminContext.Provider value={adminValue(true)}>
205
+ <InviteButton />
206
+ </AdminContext.Provider>
207
+ <AdminContext.Provider value={adminValue(false)}>
208
+ <InviteButton compact />
209
+ </AdminContext.Provider>
210
+ </AuthContext.Provider>,
211
+ );
212
+ expect(screen.queryByRole('button', { name: 'Invite' })).not.toBeInTheDocument();
213
+ });
214
+ });
@@ -1,5 +1,12 @@
1
1
  import { describe, expect, it } from 'vitest';
2
- import { FIRST_PAGE_PROMPT, chatGptPromptUrl, claudePromptUrl, firstPagePromptFor, firstPageRoute } from '../first-page-prompt';
2
+ import {
3
+ FIRST_PAGE_PROMPT,
4
+ chatGptPromptUrl,
5
+ claudePromptUrl,
6
+ firstPagePromptFor,
7
+ firstPagePromptInFolder,
8
+ firstPageRoute,
9
+ } from '../first-page-prompt';
3
10
 
4
11
  /**
5
12
  * The first-page prompt links: the prompt must arrive in the chat exactly as
@@ -107,3 +114,51 @@ describe('firstPagePromptFor', () => {
107
114
  expect(firstPagePromptFor({ firstPagePrompt: ' ' })).toBe(FIRST_PAGE_PROMPT);
108
115
  });
109
116
  });
117
+
118
+ /**
119
+ * The request, pointed at the folder New page would write in when that is
120
+ * below the top of Knowledge: an agent writing as the person must try where
121
+ * they may write.
122
+ */
123
+ describe('the first-page request in a folder', () => {
124
+ it('names the folder in the generic request', () => {
125
+ expect(firstPagePromptInFolder(FIRST_PAGE_PROMPT, 'Sales')).toBe(
126
+ "Using our Hexis knowledge base, write a page in Knowledge/Sales about our company: what we do, who we work with, and our main products. Ask me for anything you don't know, then save it.",
127
+ );
128
+ expect(firstPagePromptInFolder(FIRST_PAGE_PROMPT, 'Sales/Team')).toContain('write a page in Knowledge/Sales/Team about');
129
+ });
130
+
131
+ it('leaves the request as it is at the top of Knowledge', () => {
132
+ expect(firstPagePromptInFolder(FIRST_PAGE_PROMPT, null)).toBe(FIRST_PAGE_PROMPT);
133
+ });
134
+
135
+ it('adds the place to a starter pack’s request that does not say it', () => {
136
+ expect(firstPagePromptInFolder('Using our Hexis knowledge base, fill in the Customers page.', 'Sales')).toBe(
137
+ 'Using our Hexis knowledge base, fill in the Customers page. Save it in Knowledge/Sales.',
138
+ );
139
+ });
140
+
141
+ it('points a built-in pack’s "page in Knowledge" at the folder, naming one place', () => {
142
+ const sales =
143
+ "Using our Hexis knowledge base, fill in the Customers page in Knowledge for our sales team: who buys from us. Ask me for anything you don't know, then save it.";
144
+ const out = firstPagePromptInFolder(sales, 'Sales');
145
+ expect(out).toBe(sales.replace('page in Knowledge for', 'page in Knowledge/Sales for'));
146
+ expect(out).not.toContain('Save it in');
147
+ });
148
+
149
+ it('matches "in Knowledge" in any case, keeping the request’s own casing', () => {
150
+ expect(firstPagePromptInFolder('Write a page IN KNOWLEDGE about us.', 'Sales')).toBe(
151
+ 'Write a page IN KNOWLEDGE/Sales about us.',
152
+ );
153
+ expect(firstPagePromptInFolder('Write a page in knowledge.', 'Sales')).toBe('Write a page in knowledge/Sales.');
154
+ });
155
+
156
+ it('does not mistake "knowledge base" or a name starting with Knowledge for the folder', () => {
157
+ expect(firstPagePromptInFolder('Write a page in Knowledge Management.', 'Sales')).toBe(
158
+ 'Write a page in Knowledge Management. Save it in Knowledge/Sales.',
159
+ );
160
+ expect(firstPagePromptInFolder('Look in knowledge base, then write it in Knowledge.', 'Sales')).toBe(
161
+ 'Look in knowledge base, then write it in Knowledge/Sales.',
162
+ );
163
+ });
164
+ });