@bevel-software/platform-core-frontend 0.8.0 → 0.9.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 (36) hide show
  1. package/package.json +2 -2
  2. package/src/core/registry.ts +16 -4
  3. package/src/modules/admin/state/admin.context.tsx +15 -0
  4. package/src/modules/library/__tests__/PluginPage.test.tsx +97 -6
  5. package/src/modules/library/__tests__/PluginsIndexPage.test.tsx +90 -10
  6. package/src/modules/library/__tests__/PluginsSidebar.contextmenu.test.tsx +1 -0
  7. package/src/modules/library/__tests__/PluginsSidebar.locked.test.tsx +1 -0
  8. package/src/modules/library/__tests__/PluginsSidebar.test.tsx +29 -0
  9. package/src/modules/library/__tests__/library-data.test.ts +82 -0
  10. package/src/modules/library/components/LibraryCard.tsx +6 -1
  11. package/src/modules/library/components/LibraryLayout.tsx +11 -2
  12. package/src/modules/library/components/NewSkillPanel.tsx +18 -0
  13. package/src/modules/library/components/PageActions.tsx +31 -8
  14. package/src/modules/library/components/PersonalPluginPage.tsx +14 -4
  15. package/src/modules/library/components/PluginJoinRequests.tsx +22 -1
  16. package/src/modules/library/components/PluginPage.tsx +42 -5
  17. package/src/modules/library/components/PluginsIndexPage.tsx +46 -3
  18. package/src/modules/library/components/PluginsSidebar.tsx +50 -0
  19. package/src/modules/library/components/plugin-page-parts.tsx +184 -4
  20. package/src/modules/library/routes/LibraryRoutes.tsx +2 -2
  21. package/src/modules/library/state/library-data.tsx +21 -0
  22. package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +318 -0
  23. package/src/modules/onboarding/components/CreatorWelcomePage.tsx +143 -0
  24. package/src/modules/onboarding/components/WelcomePage.tsx +11 -14
  25. package/src/modules/onboarding/components/WelcomeRoute.tsx +57 -0
  26. package/src/modules/onboarding/welcome-state.ts +36 -0
  27. package/src/modules/setup/__tests__/setup.test.tsx +203 -0
  28. package/src/modules/setup/components/SetupScreen.tsx +235 -68
  29. package/src/modules/workspace/components/FileRoute.tsx +8 -1
  30. package/src/modules/workspace/components/FileViewer.tsx +95 -38
  31. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +20 -0
  32. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +227 -18
  33. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +25 -0
  34. package/src/modules/workspace/routing/kb-routes.ts +23 -1
  35. package/src/modules/workspace/utils/fileTree.ts +51 -0
  36. package/src/shared/components/Surface.tsx +15 -0
@@ -0,0 +1,318 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { render, renderHook, screen, waitFor } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
5
+ import type { ReactNode } from 'react';
6
+ import { AdminContext, type AdminContextValue } from '../../admin/state/admin.context';
7
+ import { AuthContext } from '../../auth/state/auth.context';
8
+ import { authValue } from '../../library/__tests__/auth-harness';
9
+ import { LibraryContext } from '../../library/state/library-context';
10
+ import type { LibraryContextValue } from '../../library/state/library-data';
11
+ import { LibraryToastProvider } from '../../library/state/toast';
12
+ import { setSidebarCollapsed, useSidebar } from '../../layout/state/sidebar';
13
+ import { WelcomeRoute } from '../components/WelcomeRoute';
14
+ import { WELCOME_PATH } from '../paths';
15
+ import { resetOnboardingForTests } from '../state/onboarding';
16
+
17
+ const serviceMocks = vi.hoisted(() => ({
18
+ createPlugin: vi.fn(),
19
+ createEmptySkill: vi.fn(),
20
+ }));
21
+
22
+ vi.mock('../../library/services/plugins.api', async (importOriginal) => {
23
+ const actual = await importOriginal<typeof import('../../library/services/plugins.api')>();
24
+ return { ...actual, createPlugin: serviceMocks.createPlugin };
25
+ });
26
+
27
+ vi.mock('../../library/services/library.api', async (importOriginal) => {
28
+ const actual = await importOriginal<typeof import('../../library/services/library.api')>();
29
+ return { ...actual, createEmptySkill: serviceMocks.createEmptySkill };
30
+ });
31
+
32
+ function library(over: Partial<LibraryContextValue> = {}): LibraryContextValue {
33
+ return {
34
+ loading: false,
35
+ error: null,
36
+ skills: [],
37
+ pendingSkills: [],
38
+ tools: [],
39
+ ownedSkills: new Set(),
40
+ allowedToolsBySkill: new Map(),
41
+ crs: [],
42
+ myCrNumbers: new Set(),
43
+ reload: vi.fn(),
44
+ items: [],
45
+ pluginSummaries: [],
46
+ pluginsLoading: false,
47
+ pluginsError: null,
48
+ reloadPlugins: vi.fn(),
49
+ ...over,
50
+ };
51
+ }
52
+
53
+ function admin(over: Partial<AdminContextValue> = {}): AdminContextValue {
54
+ return {
55
+ isAdmin: true,
56
+ isAdminLoading: false,
57
+ unreadCount: 0,
58
+ lastSeen: null,
59
+ markSeen: vi.fn(),
60
+ refresh: vi.fn(),
61
+ rolesConfigCorrupted: false,
62
+ rolesConfigErrors: [],
63
+ runRolesRecovery: vi.fn(),
64
+ ...over,
65
+ };
66
+ }
67
+
68
+ function LocationProbe() {
69
+ return <div aria-label="pathname">{useLocation().pathname}</div>;
70
+ }
71
+
72
+ function providers(
73
+ children: ReactNode,
74
+ options: { admin?: Partial<AdminContextValue>; library?: Partial<LibraryContextValue> } = {},
75
+ ) {
76
+ return (
77
+ <AuthContext.Provider
78
+ value={authValue({
79
+ user: {
80
+ id: 'u1',
81
+ email: 'juan@bevel.software',
82
+ name: 'Juan Viera',
83
+ onboardingDone: false,
84
+ },
85
+ })}
86
+ >
87
+ <AdminContext.Provider value={admin(options.admin)}>
88
+ <LibraryContext.Provider value={library(options.library)}>
89
+ <LibraryToastProvider>{children}</LibraryToastProvider>
90
+ </LibraryContext.Provider>
91
+ </AdminContext.Provider>
92
+ </AuthContext.Provider>
93
+ );
94
+ }
95
+
96
+ interface WelcomeOptions {
97
+ greeted?: boolean;
98
+ /** Overrides the greeting arrival's route state — e.g. to carry `returnTo`. */
99
+ routeState?: Record<string, unknown>;
100
+ admin?: Partial<AdminContextValue>;
101
+ library?: Partial<LibraryContextValue>;
102
+ }
103
+
104
+ /**
105
+ * The whole tree, as one builder — so a test that re-renders with different
106
+ * options reuses the exact router + provider composition instead of
107
+ * hand-assembling a second copy that can drift from this one.
108
+ */
109
+ function welcomeUi(options: WelcomeOptions = {}) {
110
+ const entry = options.greeted === false
111
+ ? WELCOME_PATH
112
+ : { pathname: WELCOME_PATH, state: options.routeState ?? { greeting: true } };
113
+
114
+ return (
115
+ <MemoryRouter initialEntries={[entry]}>
116
+ {providers(
117
+ <>
118
+ <Routes>
119
+ <Route path={WELCOME_PATH} element={<WelcomeRoute />} />
120
+ <Route path="/skills-and-tools/plugins/:plugin" element={<div>plugin page</div>} />
121
+ <Route path="/skills-and-tools/skills/:skill" element={<div>skill page</div>} />
122
+ </Routes>
123
+ <LocationProbe />
124
+ </>,
125
+ options,
126
+ )}
127
+ </MemoryRouter>
128
+ );
129
+ }
130
+
131
+ function renderWelcome(options: WelcomeOptions = {}) {
132
+ return render(welcomeUi(options));
133
+ }
134
+
135
+ beforeEach(() => {
136
+ resetOnboardingForTests();
137
+ setSidebarCollapsed(false, true);
138
+ serviceMocks.createPlugin.mockReset();
139
+ serviceMocks.createPlugin.mockResolvedValue({ folder: 'Design' });
140
+ serviceMocks.createEmptySkill.mockReset();
141
+ serviceMocks.createEmptySkill.mockResolvedValue({
142
+ repoRelativePath: 'Plugins/personal-u1/weekly-report/SKILL.md',
143
+ workspacePath: 'knowledge-base/Plugins/personal-u1/weekly-report/SKILL.md',
144
+ branch: 'dev',
145
+ direct: true,
146
+ });
147
+ });
148
+
149
+ describe('creator welcome routing', () => {
150
+ it('welcomes an admin to build a truly empty library', () => {
151
+ renderWelcome();
152
+
153
+ expect(screen.getByRole('heading', { name: 'Welcome, Juan' })).toBeInTheDocument();
154
+ expect(screen.getByText(/Build the shared library/)).toBeInTheDocument();
155
+ expect(screen.getByRole('button', { name: 'Create a plugin' })).toBeInTheDocument();
156
+ expect(screen.getByRole('button', { name: 'Create a skill' })).toBeInTheDocument();
157
+ expect(screen.queryByRole('radiogroup', { name: 'Your agent' })).toBeNull();
158
+ });
159
+
160
+ it('keeps the external-agent welcome for non-admin users', () => {
161
+ renderWelcome({ admin: { isAdmin: false } });
162
+
163
+ expect(screen.getByRole('radiogroup', { name: 'Your agent' })).toBeInTheDocument();
164
+ expect(screen.queryByRole('button', { name: 'Create a plugin' })).toBeNull();
165
+ });
166
+
167
+ it('keeps the external-agent welcome when the admin already has content', () => {
168
+ renderWelcome({
169
+ library: {
170
+ items: [
171
+ {
172
+ kind: 'skill',
173
+ id: 'roadmap',
174
+ name: 'roadmap',
175
+ description: 'Keeps the roadmap current.',
176
+ owned: true,
177
+ status: { state: 'ok', text: 'Ready' },
178
+ plugin: null,
179
+ path: 'Skills/roadmap',
180
+ },
181
+ ],
182
+ },
183
+ });
184
+
185
+ expect(screen.getByRole('radiogroup', { name: 'Your agent' })).toBeInTheDocument();
186
+ expect(screen.queryByRole('button', { name: 'Create a plugin' })).toBeNull();
187
+ });
188
+
189
+ it('does not mistake loading or failed plugin data for an empty library', () => {
190
+ // While the ADMIN verdict is unknown the hold says nothing about a
191
+ // library — the reader may be headed for the agent welcome, where theirs
192
+ // is beside the point.
193
+ const { rerender } = renderWelcome({ admin: { isAdminLoading: true } });
194
+ expect(screen.getByText('One moment…')).toBeInTheDocument();
195
+
196
+ rerender(welcomeUi({ library: { pluginsError: "Couldn't load plugins." } }));
197
+
198
+ expect(screen.getByRole('radiogroup', { name: 'Your agent' })).toBeInTheDocument();
199
+ });
200
+
201
+ it("names the wait truthfully once the verdict says admin — it IS their library loading", () => {
202
+ renderWelcome({ library: { loading: true } });
203
+ expect(screen.getByText('Preparing your library…')).toBeInTheDocument();
204
+ });
205
+
206
+ it('keeps a carried deep link out of the creator welcome', () => {
207
+ // Only `WelcomePage` has the exit that honors `returnTo`. An empty-library
208
+ // admin would otherwise be routed to the creator page — and lose the page
209
+ // their SSO round-trip was carrying them to.
210
+ renderWelcome({
211
+ routeState: {
212
+ greeting: true,
213
+ returnTo: '/workspace/main/knowledge-base/KnowledgeBase/Start here.md',
214
+ },
215
+ });
216
+ expect(screen.getByRole('radiogroup', { name: 'Your agent' })).toBeInTheDocument();
217
+ expect(screen.getByRole('button', { name: /Continue to your link/ })).toBeInTheDocument();
218
+ expect(screen.queryByText(/Build the shared library/)).toBeNull();
219
+ });
220
+
221
+ it('uses the external-agent welcome for later visits from its reminder', () => {
222
+ renderWelcome({ greeted: false });
223
+
224
+ expect(screen.getByRole('radiogroup', { name: 'Your agent' })).toBeInTheDocument();
225
+ expect(screen.queryByRole('button', { name: 'Create a plugin' })).toBeNull();
226
+ });
227
+
228
+ it('collapses the sidebar before the creator welcome is shown', () => {
229
+ renderWelcome();
230
+ expect(renderHook(() => useSidebar()).result.current).toMatchObject({
231
+ collapsed: true,
232
+ instant: true,
233
+ });
234
+ });
235
+ });
236
+
237
+ describe('creator welcome actions', () => {
238
+ it('creates a plugin through the shared dialog and refreshes both indexes', async () => {
239
+ const data = library();
240
+ const user = userEvent.setup();
241
+ renderWelcome({ library: data });
242
+
243
+ await user.click(screen.getByRole('button', { name: 'Create a plugin' }));
244
+ await user.type(screen.getByRole('textbox', { name: 'Plugin name' }), 'Design');
245
+ await user.click(screen.getByRole('button', { name: 'Create plugin' }));
246
+
247
+ await waitFor(() => expect(serviceMocks.createPlugin).toHaveBeenCalledWith('Design'));
248
+ expect(data.reload).toHaveBeenCalledOnce();
249
+ expect(data.reloadPlugins).toHaveBeenCalledOnce();
250
+ expect(screen.getByLabelText('pathname')).toHaveTextContent(
251
+ '/skills-and-tools/plugins/Design',
252
+ );
253
+ });
254
+
255
+ it('creates a personal skill and opens its skill page', async () => {
256
+ const data = library();
257
+ const user = userEvent.setup();
258
+ renderWelcome({ library: data });
259
+
260
+ await user.click(screen.getByRole('button', { name: 'Create a skill' }));
261
+ expect(screen.getByRole('dialog', { name: 'New skill' })).toBeInTheDocument();
262
+ await user.type(screen.getByRole('textbox', { name: 'Skill name' }), 'weekly-report');
263
+ await user.click(screen.getByRole('button', { name: 'Create' }));
264
+
265
+ await waitFor(() =>
266
+ expect(serviceMocks.createEmptySkill).toHaveBeenCalledWith({
267
+ personal: true,
268
+ name: 'weekly-report',
269
+ userEmail: 'juan@bevel.software',
270
+ userName: 'Juan Viera',
271
+ }),
272
+ );
273
+ expect(data.reload).toHaveBeenCalledOnce();
274
+ // The skill's canonical address is its workspace FILE url, not the legacy
275
+ // `skills/:name` route — that one survives only as a redirect. The dialog
276
+ // owns this navigation, so the welcome page inherits whatever the rest of
277
+ // the Library does, which is the point of routing through it.
278
+ expect(screen.getByLabelText('pathname')).toHaveTextContent(
279
+ '/workspace/target-company-state/knowledge-base/Plugins/personal-u1/weekly-report/SKILL.md',
280
+ );
281
+ });
282
+
283
+ it('holds the New skill dialog open while creation is pending', async () => {
284
+ // A create that has started finishes even if the dialog goes away — and
285
+ // then NAVIGATES. Every way out must be barred until it settles, or a
286
+ // dismissal turns into being carried to a page you closed the door on.
287
+ let release!: () => void;
288
+ serviceMocks.createEmptySkill.mockImplementation(
289
+ () =>
290
+ new Promise((resolve) => {
291
+ release = () =>
292
+ resolve({
293
+ repoRelativePath: 'Plugins/personal-u1/weekly-report/SKILL.md',
294
+ workspacePath: 'knowledge-base/Plugins/personal-u1/weekly-report/SKILL.md',
295
+ branch: 'dev',
296
+ direct: true,
297
+ });
298
+ }),
299
+ );
300
+ const user = userEvent.setup();
301
+ renderWelcome();
302
+
303
+ await user.click(screen.getByRole('button', { name: 'Create a skill' }));
304
+ await user.type(screen.getByRole('textbox', { name: 'Skill name' }), 'weekly-report');
305
+ await user.click(screen.getByRole('button', { name: 'Create' }));
306
+
307
+ for (const door of screen.getAllByRole('button', { name: /close/i })) {
308
+ expect(door).toBeDisabled();
309
+ }
310
+
311
+ release();
312
+ await waitFor(() =>
313
+ expect(screen.getByLabelText('pathname')).toHaveTextContent(
314
+ '/workspace/target-company-state/knowledge-base/Plugins/personal-u1/weekly-report/SKILL.md',
315
+ ),
316
+ );
317
+ });
318
+ });
@@ -0,0 +1,143 @@
1
+ import { useEffect, useMemo, useState } from 'react';
2
+ import { Sparkles, Users } from 'lucide-react';
3
+ import { Button, Dialog, Surface } from '../../../shared/components';
4
+ import { useAuth } from '../../auth/state/auth.context';
5
+ import { NewPluginDialog } from '../../library/components/NewPluginDialog';
6
+ import { NewSkillPanel } from '../../library/components/NewSkillPanel';
7
+ import { useLibrary } from '../../library/state/library-data';
8
+ import { displayFirstName } from '../../library/utils/personal-plugin';
9
+ import { useOnboarding } from '../state/onboarding';
10
+
11
+ /**
12
+ * The first useful screen in an empty deployment.
13
+ *
14
+ * A regular account needs to connect an agent before the library becomes
15
+ * useful. The first admin has a different job: make the shared structure that
16
+ * everyone else will find. This page offers the two smallest real beginnings,
17
+ * using the same plugin and skill creation flows available everywhere else.
18
+ */
19
+ export function CreatorWelcomePage() {
20
+ const { user } = useAuth();
21
+ const onboarding = useOnboarding();
22
+ const data = useLibrary();
23
+ const [newPluginOpen, setNewPluginOpen] = useState(false);
24
+ const [newSkillOpen, setNewSkillOpen] = useState(false);
25
+ /**
26
+ * The skill panel's in-flight state, lifted. A create that has started
27
+ * finishes even if the dialog goes away — and then navigates. Holding the
28
+ * dialog's close doors shut while it runs (`Dialog.busy` + the footer
29
+ * button) is what keeps "dismiss" from turning into "get carried to a page
30
+ * you closed the door on".
31
+ */
32
+ const [newSkillBusy, setNewSkillBusy] = useState(false);
33
+
34
+ const { markWelcomed } = onboarding;
35
+ useEffect(() => {
36
+ markWelcomed();
37
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- one idempotent welcome record per mount
38
+ }, []);
39
+
40
+ const pluginNames = useMemo(
41
+ () => [
42
+ ...new Set([
43
+ ...data.pluginSummaries.map((plugin) => plugin.name),
44
+ ...data.items.flatMap((item) => (item.plugin ? [item.plugin] : [])),
45
+ ]),
46
+ ],
47
+ [data.pluginSummaries, data.items],
48
+ );
49
+ const skillNames = useMemo(
50
+ () => data.items.filter((item) => item.kind === 'skill').map((item) => item.name),
51
+ [data.items],
52
+ );
53
+ const firstName = displayFirstName(user?.name) || 'there';
54
+
55
+ return (
56
+ <div className="mx-auto mt-[9vh] max-w-[580px] pb-14">
57
+ <h1 className="text-display font-bold">Welcome, {firstName}</h1>
58
+ <p className="mt-3 max-w-[54ch] text-lede text-ink-muted">
59
+ Build the shared library your team and AI agents work from. Start with a plugin for a
60
+ team or project, or create a skill in your own space.
61
+ </p>
62
+
63
+ <div className="mt-9 text-label uppercase text-ink-faint">Choose where to start</div>
64
+ <div className="mt-2.5 grid gap-3 sm:grid-cols-2">
65
+ <Surface as="section" elevation="none" padded className="flex min-h-48 flex-col">
66
+ <Users size={19} className="text-accent" aria-hidden="true" />
67
+ <h2 className="mt-3 text-strong font-semibold text-ink">Create a plugin</h2>
68
+ <p className="mt-1 text-ui text-ink-muted">
69
+ Organize skills and tools for a team, then invite the people who need them.
70
+ </p>
71
+ <Button
72
+ variant="primary"
73
+ className="mt-auto self-start"
74
+ onClick={() => setNewPluginOpen(true)}
75
+ >
76
+ Create a plugin
77
+ </Button>
78
+ </Surface>
79
+
80
+ <Surface as="section" elevation="none" padded className="flex min-h-48 flex-col">
81
+ <Sparkles size={19} className="text-accent" aria-hidden="true" />
82
+ <h2 className="mt-3 text-strong font-semibold text-ink">Create a skill</h2>
83
+ <p className="mt-1 text-ui text-ink-muted">
84
+ Capture repeatable instructions for an AI agent. You can add the skill to a plugin
85
+ later.
86
+ </p>
87
+ <Button
88
+ variant="outline"
89
+ className="mt-auto self-start"
90
+ onClick={() => setNewSkillOpen(true)}
91
+ >
92
+ Create a skill
93
+ </Button>
94
+ </Surface>
95
+ </div>
96
+
97
+ {newPluginOpen && (
98
+ <NewPluginDialog
99
+ existing={pluginNames}
100
+ onClose={() => setNewPluginOpen(false)}
101
+ onCreated={() => {
102
+ data.reload();
103
+ data.reloadPlugins();
104
+ }}
105
+ />
106
+ )}
107
+
108
+ {newSkillOpen && (
109
+ <Dialog
110
+ open
111
+ busy={newSkillBusy}
112
+ onClose={() => setNewSkillOpen(false)}
113
+ title="New skill"
114
+ footer={
115
+ <Button
116
+ variant="quiet"
117
+ disabled={newSkillBusy}
118
+ onClick={() => setNewSkillOpen(false)}
119
+ >
120
+ Close
121
+ </Button>
122
+ }
123
+ >
124
+ <p className="text-ui text-ink-muted">
125
+ Start in your own space. You can move the skill into a shared plugin when it is ready.
126
+ </p>
127
+ <NewSkillPanel
128
+ destination={{ personal: true }}
129
+ existingSkills={skillNames}
130
+ onBusyChange={setNewSkillBusy}
131
+ onCreated={() => {
132
+ // Belt and braces on the lifted flag: the panel clears it
133
+ // itself, and clearing it again as the dialog closes means a
134
+ // later open can never inherit a stale busy state.
135
+ setNewSkillOpen(false);
136
+ setNewSkillBusy(false);
137
+ }}
138
+ />
139
+ </Dialog>
140
+ )}
141
+ </div>
142
+ );
143
+ }
@@ -1,5 +1,5 @@
1
1
  import { useEffect, useLayoutEffect, useRef, useState } from 'react';
2
- import { useLocation, useNavigate } from 'react-router-dom';
2
+ import { useNavigate } from 'react-router-dom';
3
3
  import { Check, Copy, X } from 'lucide-react';
4
4
  import { cn } from '../../../lib/utils';
5
5
  import { Button, IconButton } from '../../../shared/components';
@@ -13,6 +13,7 @@ import { setSidebarCollapsed } from '../../layout/state/sidebar';
13
13
  import { ClaudeInstallLink, mcpEndpointUrl } from '../../../shared/mcp';
14
14
  import { AGENT_CLIENTS, type AgentClient } from '../agent-clients';
15
15
  import { useOnboarding } from '../state/onboarding';
16
+ import { useWelcomeRouteState } from '../welcome-state';
16
17
 
17
18
  /**
18
19
  * The welcome page — the first thing a new account sees, once.
@@ -48,20 +49,16 @@ export function WelcomePage() {
48
49
  }, []);
49
50
 
50
51
  /**
51
- * How you got here. The automatic redirect at first sign-in is the ONE
52
- * navigation that sets it (see `RootLanding`); the sidebar pill and a typed
53
- * URL do not. Everything ceremonial on this page hangs off this flag.
54
- */
55
- const routeState = useLocation().state as { greeting?: boolean; returnTo?: string | null } | null;
56
- const greeting = routeState?.greeting === true;
57
- /**
58
- * Where the person was actually GOING when the sign-in interrupted them — a
59
- * deep link that survived the SSO round-trip (see `RootLanding`). Present
60
- * only on the greeting arrival, and it retargets both exits: a welcome that
61
- * concluded by discarding the page someone was sent is a greeting that cost
62
- * them the reason they came.
52
+ * How you got here, and where you were going — read through the shared
53
+ * parser, so this page and `WelcomeRoute` cannot drift apart about what an
54
+ * arrival carries (see `welcome-state`).
55
+ *
56
+ * `greeting` is what everything ceremonial on this page hangs off.
57
+ * `returnTo` is the deep link that survived the SSO round-trip, and it
58
+ * retargets both exits: a welcome that concluded by discarding the page
59
+ * someone was sent is a greeting that cost them the reason they came.
63
60
  */
64
- const returnTo = greeting ? (routeState?.returnTo ?? null) : null;
61
+ const { greeting, returnTo } = useWelcomeRouteState();
65
62
 
66
63
  /**
67
64
  * The entrance — and it belongs to the greeting alone.
@@ -0,0 +1,57 @@
1
+ import { useLayoutEffect } from 'react';
2
+ import { useAdmin } from '../../admin/state/admin.context';
3
+ import { setSidebarCollapsed } from '../../layout/state/sidebar';
4
+ import { useLibrary } from '../../library/state/library-data';
5
+ import { useWelcomeRouteState } from '../welcome-state';
6
+ import { CreatorWelcomePage } from './CreatorWelcomePage';
7
+ import { WelcomePage } from './WelcomePage';
8
+
9
+ /**
10
+ * Chooses the first welcome without changing what the permanent reminder does.
11
+ *
12
+ * Only RootLanding sends `greeting: true`. A later visit from the Connect your
13
+ * agent reminder has no greeting state and must always reach its existing
14
+ * instructions, even when the admin has not created anything yet.
15
+ */
16
+ export function WelcomeRoute() {
17
+ const { isAdmin, isAdminLoading = false } = useAdmin();
18
+ const data = useLibrary();
19
+ // The same reading `WelcomePage` gets — one parser, so the router and the
20
+ // page cannot disagree about whether a deep link was carried.
21
+ const { greeting, returnTo } = useWelcomeRouteState();
22
+
23
+ // Hold the sidebar out of the first painted frame while the admin and
24
+ // library checks settle. Both welcome pages use the full reading column.
25
+ useLayoutEffect(() => {
26
+ if (greeting) setSidebarCollapsed(true, true);
27
+ }, [greeting]);
28
+
29
+ // A carried deep link outranks the creator welcome, admin or not: only
30
+ // `WelcomePage` has the exit that honors `returnTo`, and a greeting that
31
+ // concluded by discarding the page someone was sent would cost them the
32
+ // reason they came. The library can be built after the link is kept.
33
+ if (!greeting || returnTo || (!isAdminLoading && !isAdmin)) return <WelcomePage />;
34
+
35
+ if (isAdminLoading || data.loading || data.pluginsLoading) {
36
+ // Two phases, two truths. While the ADMIN verdict is unknown the reader
37
+ // may be headed for the agent welcome, where their library is beside the
38
+ // point — so the hold says nothing about one. Once the verdict says
39
+ // admin, the remaining wait really is their library loading.
40
+ // A live region: the wait changes its own words as it advances from the
41
+ // admin check to the library load, and a silent swap is a change only
42
+ // sighted users are told about.
43
+ return (
44
+ <div role="status" className="py-16 text-center text-ui text-ink-faint">
45
+ {isAdminLoading ? 'One moment…' : 'Preparing your library…'}
46
+ </div>
47
+ );
48
+ }
49
+
50
+ const libraryIsEmpty =
51
+ !data.error &&
52
+ !data.pluginsError &&
53
+ data.items.length === 0 &&
54
+ data.pluginSummaries.length === 0;
55
+
56
+ return libraryIsEmpty ? <CreatorWelcomePage /> : <WelcomePage />;
57
+ }
@@ -0,0 +1,36 @@
1
+ import { useLocation } from 'react-router-dom';
2
+
3
+ /**
4
+ * What an arrival at the welcome route carries — parsed in ONE place.
5
+ *
6
+ * Two components read this state: `WelcomeRoute`, which decides WHICH welcome
7
+ * you get, and `WelcomePage`, which decides where its exits go. They have to
8
+ * agree — a router that preserves a deep link in front of a page that
9
+ * discards it (or the reverse) loses the destination silently, and neither
10
+ * side's tests would notice. So the shape and the rules live here rather than
11
+ * being re-derived from `location.state` at each call site.
12
+ */
13
+ export interface WelcomeRouteState {
14
+ /**
15
+ * How you got here. The automatic redirect at first sign-in is the ONE
16
+ * navigation that sets it (see `RootLanding`); the sidebar pill and a typed
17
+ * URL do not. Everything ceremonial on the welcome hangs off this flag.
18
+ */
19
+ greeting: boolean;
20
+ /**
21
+ * Where the person was actually GOING when the sign-in interrupted them — a
22
+ * deep link that survived the SSO round-trip (see `RootLanding`).
23
+ *
24
+ * Null unless this is the greeting arrival, and that condition is the rule
25
+ * worth centralising: a `returnTo` on a later, non-greeting visit is not a
26
+ * carried intention, it is stale state on a page someone opened themselves.
27
+ */
28
+ returnTo: string | null;
29
+ }
30
+
31
+ /** Reads the welcome contract off the current location. */
32
+ export function useWelcomeRouteState(): WelcomeRouteState {
33
+ const state = useLocation().state as { greeting?: boolean; returnTo?: string | null } | null;
34
+ const greeting = state?.greeting === true;
35
+ return { greeting, returnTo: greeting ? (state?.returnTo ?? null) : null };
36
+ }