@prenta/admin 2.8.0 → 2.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 (81) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/AdminRoot.d.ts.map +1 -1
  3. package/dist/AdminRoot.js +6 -6
  4. package/dist/AdminRoot.js.map +1 -1
  5. package/dist/__tests__/components/batch-ai-actions.test.js +4 -0
  6. package/dist/__tests__/components/batch-ai-actions.test.js.map +1 -1
  7. package/dist/__tests__/lib/batch-wizard.test.js +85 -1
  8. package/dist/__tests__/lib/batch-wizard.test.js.map +1 -1
  9. package/dist/__tests__/lib/jobs-service.test.js +19 -1
  10. package/dist/__tests__/lib/jobs-service.test.js.map +1 -1
  11. package/dist/__tests__/views/run-with-ai.render.test.d.ts +2 -0
  12. package/dist/__tests__/views/run-with-ai.render.test.d.ts.map +1 -0
  13. package/dist/__tests__/views/run-with-ai.render.test.js +711 -0
  14. package/dist/__tests__/views/run-with-ai.render.test.js.map +1 -0
  15. package/dist/components/BatchAiActions.d.ts +8 -1
  16. package/dist/components/BatchAiActions.d.ts.map +1 -1
  17. package/dist/components/BatchAiActions.js +3 -2
  18. package/dist/components/BatchAiActions.js.map +1 -1
  19. package/dist/lib/batch-wizard.d.ts +34 -0
  20. package/dist/lib/batch-wizard.d.ts.map +1 -1
  21. package/dist/lib/batch-wizard.js +97 -0
  22. package/dist/lib/batch-wizard.js.map +1 -1
  23. package/dist/lib/jobs-service.d.ts +28 -0
  24. package/dist/lib/jobs-service.d.ts.map +1 -1
  25. package/dist/lib/jobs-service.js +9 -0
  26. package/dist/lib/jobs-service.js.map +1 -1
  27. package/dist/prenta-admin.css +1 -1
  28. package/dist/views/CollectionList.d.ts +3 -1
  29. package/dist/views/CollectionList.d.ts.map +1 -1
  30. package/dist/views/CollectionList.js +5 -2
  31. package/dist/views/CollectionList.js.map +1 -1
  32. package/dist/views/Jobs/DrawerOverview.d.ts +6 -2
  33. package/dist/views/Jobs/DrawerOverview.d.ts.map +1 -1
  34. package/dist/views/Jobs/DrawerOverview.js +6 -3
  35. package/dist/views/Jobs/DrawerOverview.js.map +1 -1
  36. package/dist/views/Jobs/DrawerResults.d.ts +13 -3
  37. package/dist/views/Jobs/DrawerResults.d.ts.map +1 -1
  38. package/dist/views/Jobs/DrawerResults.js +37 -3
  39. package/dist/views/Jobs/DrawerResults.js.map +1 -1
  40. package/dist/views/Jobs/JobDrawer.d.ts +4 -1
  41. package/dist/views/Jobs/JobDrawer.d.ts.map +1 -1
  42. package/dist/views/Jobs/JobDrawer.js +2 -2
  43. package/dist/views/Jobs/JobDrawer.js.map +1 -1
  44. package/dist/views/Jobs/RunWithAi.d.ts +25 -0
  45. package/dist/views/Jobs/RunWithAi.d.ts.map +1 -0
  46. package/dist/views/Jobs/RunWithAi.js +46 -0
  47. package/dist/views/Jobs/RunWithAi.js.map +1 -0
  48. package/dist/views/Jobs.d.ts +3 -1
  49. package/dist/views/Jobs.d.ts.map +1 -1
  50. package/dist/views/Jobs.js +42 -8
  51. package/dist/views/Jobs.js.map +1 -1
  52. package/dist/views/MediaBrowser.d.ts +5 -1
  53. package/dist/views/MediaBrowser.d.ts.map +1 -1
  54. package/dist/views/MediaBrowser.js +6 -2
  55. package/dist/views/MediaBrowser.js.map +1 -1
  56. package/dist/views/Pages/PagesListView.d.ts +5 -1
  57. package/dist/views/Pages/PagesListView.d.ts.map +1 -1
  58. package/dist/views/Pages/PagesListView.js +7 -4
  59. package/dist/views/Pages/PagesListView.js.map +1 -1
  60. package/dist/views/Posts/PostsListView.d.ts +5 -1
  61. package/dist/views/Posts/PostsListView.d.ts.map +1 -1
  62. package/dist/views/Posts/PostsListView.js +7 -4
  63. package/dist/views/Posts/PostsListView.js.map +1 -1
  64. package/package.json +3 -3
  65. package/src/AdminRoot.tsx +20 -4
  66. package/src/__tests__/components/batch-ai-actions.test.tsx +10 -0
  67. package/src/__tests__/lib/batch-wizard.test.ts +129 -0
  68. package/src/__tests__/lib/jobs-service.test.ts +20 -0
  69. package/src/__tests__/views/run-with-ai.render.test.tsx +832 -0
  70. package/src/components/BatchAiActions.tsx +15 -2
  71. package/src/lib/batch-wizard.ts +128 -0
  72. package/src/lib/jobs-service.ts +35 -0
  73. package/src/views/CollectionList.tsx +20 -1
  74. package/src/views/Jobs/DrawerOverview.tsx +16 -3
  75. package/src/views/Jobs/DrawerResults.tsx +71 -2
  76. package/src/views/Jobs/JobDrawer.tsx +5 -1
  77. package/src/views/Jobs/RunWithAi.tsx +89 -0
  78. package/src/views/Jobs.tsx +58 -10
  79. package/src/views/MediaBrowser.tsx +20 -1
  80. package/src/views/Pages/PagesListView.tsx +28 -3
  81. package/src/views/Posts/PostsListView.tsx +26 -3
@@ -0,0 +1,711 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // @vitest-environment happy-dom
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4
+ import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
5
+ const server = {
6
+ jobs: [],
7
+ details: {},
8
+ /** `GET /seo/issues/batch-targets`; null answers 500. */
9
+ targets: [],
10
+ calls: [],
11
+ };
12
+ function iso(offsetMs = 0) {
13
+ return new Date(Date.now() + offsetMs).toISOString();
14
+ }
15
+ /** A batch the way `POST /jobs/batch-ai` returns it: queued, no total until its first slice. */
16
+ function queued(body) {
17
+ const ids = (body.filter?.documentIds ?? []).slice();
18
+ const titles = {
19
+ meta: 'Rewrite meta descriptions',
20
+ alt: 'Generate image alt text',
21
+ titles: 'Shorten long titles',
22
+ };
23
+ return {
24
+ id: 'job_new',
25
+ type: 'batch-ai',
26
+ status: 'queued',
27
+ title: titles[body.operation] ?? 'Batch AI changes',
28
+ scope: `${ids.length} selected`,
29
+ runAt: iso(),
30
+ attempts: 0,
31
+ maxAttempts: 3,
32
+ progress: { done: 0, total: 0, unit: 'documents', cursor: null, completed: 0 },
33
+ lastError: null,
34
+ explain: null,
35
+ summary: null,
36
+ lockedAt: null,
37
+ cancelRequestedAt: null,
38
+ cancelledBy: null,
39
+ createdBy: { id: 'u1', name: 'Brandon West', initials: 'BW' },
40
+ createdAt: iso(),
41
+ updatedAt: iso(),
42
+ finishedAt: null,
43
+ usage: { tokensIn: 0, tokensOut: 0 },
44
+ payload: {
45
+ operation: body.operation,
46
+ instruction: null,
47
+ source: body.source,
48
+ statusFilter: body.statusFilter,
49
+ documentIds: ids,
50
+ review: 'review',
51
+ onApprove: 'draft',
52
+ },
53
+ review: { pending: 0, approved: 0, rejected: 0 },
54
+ };
55
+ }
56
+ function cmsApiStub(endpoint, init = {}) {
57
+ const method = (init.method ?? 'GET').toUpperCase();
58
+ const body = typeof init.body === 'string' ? JSON.parse(init.body) : undefined;
59
+ server.calls.push({ endpoint, method, body });
60
+ const url = new URL(endpoint, 'http://x');
61
+ if (url.pathname === '/jobs/batch-ai/estimate') {
62
+ const count = url.searchParams.get('documentIds')?.split(',').length ?? 0;
63
+ return {
64
+ data: {
65
+ count,
66
+ sample: [{ title: 'First', url: '/first' }],
67
+ tokens: count * 900,
68
+ minutes: count,
69
+ pctOfMonthlyLimit: 1,
70
+ },
71
+ status: 200,
72
+ };
73
+ }
74
+ if (url.pathname === '/jobs/batch-ai' && method === 'POST') {
75
+ const job = queued(body);
76
+ server.jobs = [job, ...server.jobs];
77
+ return { data: job, status: 201 };
78
+ }
79
+ if (url.pathname === '/seo/issues/batch-targets') {
80
+ return server.targets
81
+ ? { data: { targets: server.targets }, status: 200 }
82
+ : { error: 'Internal server error', status: 500 };
83
+ }
84
+ const events = url.pathname.match(/^\/jobs\/([^/]+)\/events$/);
85
+ if (events)
86
+ return { data: { events: [] }, status: 200 };
87
+ const one = url.pathname.match(/^\/jobs\/([^/]+)$/);
88
+ if (one && method === 'GET') {
89
+ const job = server.jobs.find((entry) => entry.id === one[1]);
90
+ return job
91
+ ? { data: { ...job, ...server.details[job.id] }, status: 200 }
92
+ : { error: 'Job not found', status: 404 };
93
+ }
94
+ return { error: `unexpected ${method} ${endpoint}`, status: 404 };
95
+ }
96
+ vi.mock('../../lib/api.js', () => ({
97
+ getApiBase: () => '/api/cms',
98
+ cmsApi: vi.fn(async (endpoint, init) => cmsApiStub(endpoint, init)),
99
+ }));
100
+ const toast = vi.hoisted(() => Object.assign(vi.fn(), {
101
+ error: vi.fn(),
102
+ success: vi.fn(),
103
+ info: vi.fn(),
104
+ promise: vi.fn(),
105
+ }));
106
+ vi.mock('sonner', () => ({ toast }));
107
+ function post(id, title, postTypeId = 'articles') {
108
+ return {
109
+ id,
110
+ postTypeId,
111
+ postTypeName: postTypeId === 'articles' ? 'Article' : 'News',
112
+ postTypeAccentColor: 'blue',
113
+ title,
114
+ slug: id,
115
+ publicPath: `/blog/${id}`,
116
+ authorName: 'Author',
117
+ authorInitials: 'AU',
118
+ status: 'PUBLISHED',
119
+ updatedDate: '2026-01-01T00:00:00.000Z',
120
+ seoScore: 80,
121
+ };
122
+ }
123
+ const posts = vi.hoisted(() => ({ list: [] }));
124
+ vi.mock('../../lib/posts-service.js', () => ({
125
+ fetchPosts: async () => ({
126
+ posts: posts.list,
127
+ total: posts.list.length,
128
+ types: [
129
+ { slug: 'articles', name: 'Article', postCount: 2 },
130
+ { slug: 'news', name: 'News', postCount: 1 },
131
+ ],
132
+ authors: [],
133
+ }),
134
+ bulkUpdatePosts: async () => ({ ok: 0, failed: 0 }),
135
+ bulkDeletePosts: async () => ({ ok: 0, failed: 0 }),
136
+ }));
137
+ const fetchPagesDataset = vi.hoisted(() => vi.fn());
138
+ vi.mock('../../lib/pages-service.js', async (importOriginal) => ({
139
+ ...(await importOriginal()),
140
+ fetchPagesDataset: () => fetchPagesDataset(),
141
+ }));
142
+ const MEDIA = [
143
+ { id: 'm1', name: 'harbor.jpg', type: 'image/jpeg', url: '/u/harbor.jpg' },
144
+ { id: 'm2', name: 'team.png', type: 'image/png', url: '/u/team.png' },
145
+ { id: 'm3', name: 'menu.pdf', type: 'application/pdf', url: '/u/menu.pdf' },
146
+ ].map((item) => ({
147
+ ...item,
148
+ size: '1 KB',
149
+ sizeBytes: 1024,
150
+ date: '2026-01-01',
151
+ title: item.name,
152
+ usedOn: [],
153
+ }));
154
+ /** The generic collection list's rows (`GET /collections/:slug`). */
155
+ const collectionDocs = vi.hoisted(() => ({ list: [] }));
156
+ vi.mock('../../lib/useApiData.js', () => ({
157
+ useApiData: (endpoint) => ({
158
+ data: endpoint?.startsWith('/media?pageSize=100')
159
+ ? { docs: MEDIA, total: MEDIA.length }
160
+ : endpoint?.startsWith('/collections/')
161
+ ? { docs: collectionDocs.list, total: collectionDocs.list.length, nextCursor: null }
162
+ : { docs: [], total: MEDIA.length },
163
+ loading: false,
164
+ error: null,
165
+ refetch: () => { },
166
+ }),
167
+ }));
168
+ /** The Jobs list's refresh: `GET /jobs` and `GET /jobs/worker`. */
169
+ function fetchStub(url) {
170
+ const endpoint = url.replace(/^\/api\/cms/, '');
171
+ const data = endpoint.endsWith('/jobs/worker')
172
+ ? { lastTickAt: null, lastTickMs: null, nextTickAt: null, budgetMs: 20000, schedules: [] }
173
+ : { jobs: server.jobs };
174
+ return Promise.resolve({
175
+ ok: true,
176
+ status: 200,
177
+ headers: { get: () => null },
178
+ json: async () => ({ data }),
179
+ });
180
+ }
181
+ const storage = new Map();
182
+ const { PostsListView } = await import('../../views/Posts/PostsListView.js');
183
+ const { PagesListView } = await import('../../views/Pages/PagesListView.js');
184
+ const { MediaBrowser } = await import('../../views/MediaBrowser.js');
185
+ const { Jobs } = await import('../../views/Jobs.js');
186
+ const { CollectionList } = await import('../../views/CollectionList.js');
187
+ const CONFIG = {
188
+ collections: {
189
+ articles: { slug: 'articles', type: 'post', labels: { plural: 'Articles' } },
190
+ news: { slug: 'news', type: 'post', labels: { plural: 'News' } },
191
+ pages: { slug: 'pages', type: 'page', labels: { plural: 'Pages' } },
192
+ posts: { slug: 'posts', type: 'post', labels: { plural: 'Posts' } },
193
+ blog: {
194
+ slug: 'blog',
195
+ type: 'post',
196
+ labels: { singular: 'Blog post', plural: 'Blog' },
197
+ fields: { title: { type: 'text' } },
198
+ },
199
+ team: {
200
+ slug: 'team',
201
+ labels: { singular: 'Member', plural: 'Team' },
202
+ fields: { title: { type: 'text' } },
203
+ },
204
+ },
205
+ };
206
+ beforeEach(() => {
207
+ vi.stubGlobal('fetch', vi.fn(fetchStub));
208
+ vi.stubGlobal('localStorage', {
209
+ getItem: (k) => storage.get(k) ?? null,
210
+ setItem: (k, v) => void storage.set(k, String(v)),
211
+ removeItem: (k) => void storage.delete(k),
212
+ clear: () => storage.clear(),
213
+ });
214
+ server.jobs = [];
215
+ server.details = {};
216
+ server.targets = [];
217
+ server.calls = [];
218
+ posts.list = [post('a1', 'Alpha'), post('a2', 'Alpha Two'), post('n1', 'Harbor news', 'news')];
219
+ collectionDocs.list = [];
220
+ fetchPagesDataset.mockReset();
221
+ toast.mockClear();
222
+ });
223
+ afterEach(() => {
224
+ cleanup();
225
+ storage.clear();
226
+ vi.unstubAllGlobals();
227
+ });
228
+ function wizard() {
229
+ const dialog = document.querySelector('[data-batch-wizard]');
230
+ if (!dialog)
231
+ throw new Error('the wizard is not open');
232
+ return dialog;
233
+ }
234
+ function estimateQuery() {
235
+ const call = [...server.calls]
236
+ .reverse()
237
+ .find((c) => c.endpoint.startsWith('/jobs/batch-ai/estimate'));
238
+ if (!call)
239
+ throw new Error('no estimate');
240
+ return Object.fromEntries(new URL(call.endpoint, 'http://x').searchParams);
241
+ }
242
+ function checkedOperation(dialog) {
243
+ return within(dialog).getAllByRole('radio').find((r) => r.checked).value;
244
+ }
245
+ async function toStep2(dialog, source) {
246
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Continue' }));
247
+ await within(dialog).findByText(`${source} match`);
248
+ }
249
+ async function queue(dialog, n) {
250
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Continue' }));
251
+ fireEvent.click(await within(dialog).findByRole('button', { name: `Queue ${n} documents` }));
252
+ await waitFor(() => expect(document.querySelector('[data-batch-wizard]')).toBeNull());
253
+ }
254
+ function runWithAi() {
255
+ return screen.getByRole('button', { name: /Run with AI…/ });
256
+ }
257
+ describe('Posts: Run with AI…', () => {
258
+ async function pick(...titles) {
259
+ for (const title of titles)
260
+ fireEvent.click(await screen.findByLabelText(`Select "${title}"`));
261
+ }
262
+ it('replaces Meta descriptions and Summaries, keeps Alt text, and opens the wizard on the picked posts', async () => {
263
+ render(_jsx(PostsListView, { onNavigate: () => { }, role: "EDITOR", config: CONFIG }));
264
+ await pick('Alpha', 'Alpha Two');
265
+ expect(screen.getByText('2 selected')).toBeTruthy();
266
+ expect(screen.queryByRole('button', { name: 'Meta descriptions' })).toBeNull();
267
+ expect(screen.queryByRole('button', { name: 'Summaries' })).toBeNull();
268
+ expect(screen.getByRole('button', { name: 'Alt text' })).toBeTruthy();
269
+ const opener = runWithAi();
270
+ expect(opener.getAttribute('aria-haspopup')).toBe('dialog');
271
+ opener.focus();
272
+ fireEvent.click(opener);
273
+ const dialog = wizard();
274
+ expect(within(dialog).getByRole('list', { name: 'Steps' }).textContent).toContain('What to change');
275
+ expect(checkedOperation(dialog)).toBe('meta');
276
+ expect(within(dialog).getByRole('radio', { name: /Generate image alt text/ })
277
+ .disabled).toBe(true);
278
+ await toStep2(dialog, 'articles');
279
+ expect(within(dialog).getByText('2 selected')).toBeTruthy();
280
+ expect(within(dialog).getByLabelText('Content').selectedOptions[0]
281
+ .textContent).toBe('Articles');
282
+ expect(estimateQuery()).toMatchObject({ source: 'articles', documentIds: 'a1,a2' });
283
+ });
284
+ it('queues, toasts a link to the job, and keeps the selection with focus back on Run with AI…', async () => {
285
+ const onNavigate = vi.fn();
286
+ render(_jsx(PostsListView, { onNavigate: onNavigate, role: "AUTHOR", config: CONFIG }));
287
+ await pick('Alpha', 'Alpha Two');
288
+ const opener = runWithAi();
289
+ opener.focus();
290
+ fireEvent.click(opener);
291
+ const dialog = wizard();
292
+ await toStep2(dialog, 'articles');
293
+ await queue(dialog, 2);
294
+ expect(server.calls.find((c) => c.endpoint === '/jobs/batch-ai').body).toMatchObject({
295
+ operation: 'meta',
296
+ source: 'articles',
297
+ statusFilter: 'all',
298
+ filter: { documentIds: ['a1', 'a2'] },
299
+ });
300
+ expect(toast).toHaveBeenCalledWith('“Rewrite meta descriptions” queued · 2 documents', {
301
+ action: { label: 'View job', onClick: expect.any(Function) },
302
+ });
303
+ const options = toast.mock.calls[0][1];
304
+ options.action.onClick();
305
+ expect(onNavigate).toHaveBeenCalledWith('/jobs?job=job_new');
306
+ expect(screen.getByText('2 selected')).toBeTruthy();
307
+ await waitFor(() => expect(document.activeElement).toBe(runWithAi()));
308
+ });
309
+ it('returns focus to Run with AI… after a click that didn’t focus it', async () => {
310
+ render(_jsx(PostsListView, { onNavigate: () => { }, role: "EDITOR", config: CONFIG }));
311
+ await pick('Alpha');
312
+ const opener = runWithAi();
313
+ // Safari doesn't focus a clicked button, and neither does fireEvent.
314
+ expect(document.activeElement).not.toBe(opener);
315
+ fireEvent.click(opener);
316
+ fireEvent.keyDown(wizard(), { key: 'Escape' });
317
+ await waitFor(() => expect(document.querySelector('[data-batch-wizard]')).toBeNull());
318
+ await waitFor(() => expect(document.activeElement).toBe(runWithAi()));
319
+ });
320
+ it('holds posts of two types, and says why', async () => {
321
+ render(_jsx(PostsListView, { onNavigate: () => { }, role: "ADMIN", config: CONFIG }));
322
+ await pick('Alpha', 'Harbor news');
323
+ const button = runWithAi();
324
+ expect(button.getAttribute('aria-disabled')).toBe('true');
325
+ const reason = document.getElementById(button.getAttribute('aria-describedby'));
326
+ expect(reason.textContent).toBe('Run with AI works on one post type at a time. Pick posts of a single type.');
327
+ fireEvent.click(button);
328
+ expect(document.querySelector('[data-batch-wizard]')).toBeNull();
329
+ });
330
+ it('shows Run with AI… only to roles that may queue jobs', async () => {
331
+ const { unmount } = render(_jsx(PostsListView, { onNavigate: () => { }, role: "VIEWER" }));
332
+ await pick('Alpha');
333
+ expect(screen.queryByRole('button', { name: /Run with AI…/ })).toBeNull();
334
+ expect(screen.getByRole('button', { name: 'Alt text' })).toBeTruthy();
335
+ unmount();
336
+ render(_jsx(PostsListView, { onNavigate: () => { } }));
337
+ await pick('Alpha');
338
+ expect(screen.queryByRole('button', { name: /Run with AI…/ })).toBeNull();
339
+ });
340
+ });
341
+ describe('Pages: Run with AI…', () => {
342
+ function page(id, title) {
343
+ return {
344
+ id,
345
+ title,
346
+ path: `/${id}`,
347
+ slug: id,
348
+ parentPageId: null,
349
+ tags: [],
350
+ primaryTagId: null,
351
+ authorId: 'u1',
352
+ authorName: 'Jane Doe',
353
+ authorInitials: 'JD',
354
+ status: 'DRAFT',
355
+ publishDate: null,
356
+ scheduledDate: null,
357
+ lastModified: '2026-01-01T00:00:00Z',
358
+ seoScore: 80,
359
+ seoTitle: null,
360
+ seoDescription: null,
361
+ templateId: null,
362
+ isHomepage: false,
363
+ isSystemPage: false,
364
+ createdAt: '2026-01-01T00:00:00Z',
365
+ updatedAt: '2026-01-01T00:00:00Z',
366
+ };
367
+ }
368
+ it('opens the wizard on the picked pages, and keeps Alt text', async () => {
369
+ fetchPagesDataset.mockResolvedValue({
370
+ pages: [page('about', 'About'), page('contact', 'Contact'), page('team', 'Team')],
371
+ tags: [],
372
+ authors: [],
373
+ });
374
+ render(_jsx(PagesListView, { onNavigate: () => { }, role: "EDITOR", config: CONFIG }));
375
+ fireEvent.click(await screen.findByLabelText('Select "About"'));
376
+ fireEvent.click(screen.getByLabelText('Select "Team"'));
377
+ expect(screen.queryByRole('button', { name: 'Meta descriptions' })).toBeNull();
378
+ expect(screen.queryByRole('button', { name: 'Summaries' })).toBeNull();
379
+ expect(screen.getByRole('button', { name: 'Alt text' })).toBeTruthy();
380
+ fireEvent.click(runWithAi());
381
+ const dialog = wizard();
382
+ expect(checkedOperation(dialog)).toBe('meta');
383
+ await toStep2(dialog, 'pages');
384
+ expect(within(dialog).getByText('2 selected')).toBeTruthy();
385
+ expect(estimateQuery()).toMatchObject({
386
+ source: 'pages',
387
+ statusFilter: 'all',
388
+ documentIds: 'about,team',
389
+ });
390
+ });
391
+ it('isn’t shown to a viewer', async () => {
392
+ fetchPagesDataset.mockResolvedValue({ pages: [page('about', 'About')], tags: [], authors: [] });
393
+ render(_jsx(PagesListView, { onNavigate: () => { }, role: "VIEWER", config: CONFIG }));
394
+ fireEvent.click(await screen.findByLabelText('Select "About"'));
395
+ expect(screen.getByText('1 selected')).toBeTruthy();
396
+ expect(screen.queryByRole('button', { name: /Run with AI…/ })).toBeNull();
397
+ });
398
+ });
399
+ describe('Media: Run with AI…', () => {
400
+ function checkbox(name) {
401
+ return screen.getByText(name).closest('tr').querySelector('input[type="checkbox"]');
402
+ }
403
+ async function renderList(role) {
404
+ render(_jsx(MediaBrowser, { onNavigate: () => { }, role: role, config: CONFIG }));
405
+ fireEvent.click(screen.getByRole('button', { name: 'List view' }));
406
+ await screen.findByText('harbor.jpg');
407
+ }
408
+ it('sends only the picked images, starting on alt text', async () => {
409
+ await renderList('EDITOR');
410
+ for (const name of ['harbor.jpg', 'team.png', 'menu.pdf'])
411
+ fireEvent.click(checkbox(name));
412
+ expect(screen.getByText('3 files selected')).toBeTruthy();
413
+ fireEvent.click(runWithAi());
414
+ const dialog = wizard();
415
+ expect(checkedOperation(dialog)).toBe('alt');
416
+ await toStep2(dialog, 'media library');
417
+ expect(within(dialog).getByText('2 selected')).toBeTruthy();
418
+ expect(estimateQuery()).toMatchObject({
419
+ operation: 'alt',
420
+ source: 'media',
421
+ documentIds: 'm1,m2',
422
+ });
423
+ await queue(dialog, 2);
424
+ expect(server.calls.find((c) => c.endpoint === '/jobs/batch-ai').body).toMatchObject({
425
+ operation: 'alt',
426
+ source: 'media',
427
+ filter: { documentIds: ['m1', 'm2'] },
428
+ });
429
+ });
430
+ it('holds a pick with no images, and says why', async () => {
431
+ await renderList('ADMIN');
432
+ fireEvent.click(checkbox('menu.pdf'));
433
+ const button = runWithAi();
434
+ expect(button.getAttribute('aria-disabled')).toBe('true');
435
+ expect(document.getElementById(button.getAttribute('aria-describedby')).textContent).toBe('Run with AI writes alt text for images. Pick at least one image.');
436
+ fireEvent.click(button);
437
+ expect(document.querySelector('[data-batch-wizard]')).toBeNull();
438
+ });
439
+ it('isn’t shown to a viewer', async () => {
440
+ await renderList('VIEWER');
441
+ fireEvent.click(checkbox('harbor.jpg'));
442
+ expect(screen.getByText('1 file selected')).toBeTruthy();
443
+ expect(screen.queryByRole('button', { name: /Run with AI…/ })).toBeNull();
444
+ });
445
+ });
446
+ describe('Collection list: Run with AI…', () => {
447
+ function rows(...titles) {
448
+ collectionDocs.list = titles.map((title, i) => ({
449
+ id: `d${i + 1}`,
450
+ title,
451
+ status: 'PUBLISHED',
452
+ updatedAt: '2026-10-01T00:00:00.000Z',
453
+ }));
454
+ }
455
+ it('runs a post collection’s picked documents, keeping only Alt text of the old buttons', async () => {
456
+ rows('Harbor guide', 'Ferry times', 'Tide tables');
457
+ render(_jsx(CollectionList, { collectionSlug: "blog", config: CONFIG, onNavigate: () => { }, role: "EDITOR" }));
458
+ fireEvent.click(await screen.findByLabelText('Select Harbor guide'));
459
+ fireEvent.click(screen.getByLabelText('Select Tide tables'));
460
+ expect(screen.queryByRole('button', { name: 'Meta descriptions' })).toBeNull();
461
+ expect(screen.queryByRole('button', { name: 'Summaries' })).toBeNull();
462
+ expect(screen.getByRole('button', { name: 'Alt text' })).toBeTruthy();
463
+ const opener = runWithAi();
464
+ opener.focus();
465
+ fireEvent.click(opener);
466
+ const dialog = wizard();
467
+ expect(checkedOperation(dialog)).toBe('meta');
468
+ await toStep2(dialog, 'blog');
469
+ expect(within(dialog).getByText('2 selected')).toBeTruthy();
470
+ expect(estimateQuery()).toMatchObject({ source: 'blog', documentIds: 'd1,d3' });
471
+ await queue(dialog, 2);
472
+ expect(toast).toHaveBeenCalledWith('“Rewrite meta descriptions” queued · 2 documents', {
473
+ action: { label: 'View job', onClick: expect.any(Function) },
474
+ });
475
+ expect(screen.getByText('2 selected')).toBeTruthy();
476
+ await waitFor(() => expect(document.activeElement).toBe(runWithAi()));
477
+ });
478
+ it('keeps all three old buttons, and no Run with AI…, on a collection the wizard can’t run on', async () => {
479
+ rows('Ada', 'Grace');
480
+ render(_jsx(CollectionList, { collectionSlug: "team", config: CONFIG, onNavigate: () => { }, role: "ADMIN" }));
481
+ fireEvent.click(await screen.findByLabelText('Select Ada'));
482
+ expect(screen.queryByRole('button', { name: /Run with AI…/ })).toBeNull();
483
+ for (const name of ['Meta descriptions', 'Alt text', 'Summaries']) {
484
+ expect(screen.getByRole('button', { name })).toBeTruthy();
485
+ }
486
+ });
487
+ it('isn’t shown to a viewer', async () => {
488
+ rows('Harbor guide');
489
+ render(_jsx(CollectionList, { collectionSlug: "blog", config: CONFIG, onNavigate: () => { }, role: "VIEWER" }));
490
+ fireEvent.click(await screen.findByLabelText('Select Harbor guide'));
491
+ expect(screen.getByText('1 selected')).toBeTruthy();
492
+ expect(screen.queryByRole('button', { name: /Run with AI…/ })).toBeNull();
493
+ expect(screen.getByRole('button', { name: 'Alt text' })).toBeTruthy();
494
+ });
495
+ });
496
+ /** A finished SEO scan, with the drawer's results. */
497
+ function scan(categories) {
498
+ const job = {
499
+ id: 'job_scan',
500
+ type: 'seo-scan',
501
+ status: 'succeeded',
502
+ title: 'SEO scan',
503
+ scope: 'All indexable pages',
504
+ runAt: iso(-3_600_000),
505
+ attempts: 0,
506
+ maxAttempts: 3,
507
+ progress: { done: 340, total: 340, unit: 'pages', cursor: null, completed: 340 },
508
+ lastError: null,
509
+ explain: null,
510
+ summary: null,
511
+ lockedAt: null,
512
+ cancelRequestedAt: null,
513
+ cancelledBy: null,
514
+ createdBy: { kind: 'cron', schedule: 'weekly-seo' },
515
+ createdAt: iso(-3_600_000),
516
+ updatedAt: iso(-3_000_000),
517
+ finishedAt: iso(-3_000_000),
518
+ usage: { tokensIn: 0, tokensOut: 0 },
519
+ payload: { trigger: 'cron' },
520
+ };
521
+ server.details.job_scan = {
522
+ results: {
523
+ score: 78,
524
+ prevScore: 74,
525
+ found: 23,
526
+ resolved: 11,
527
+ categories: categories.map((c) => ({ ...c, href: '/seo/content' })),
528
+ digest: { sentAt: iso(-3_000_000), recipients: 3 },
529
+ },
530
+ };
531
+ return job;
532
+ }
533
+ function target(type, sources, over = {}) {
534
+ return {
535
+ type,
536
+ operation: type === 'meta-title-length' ? 'titles' : 'meta',
537
+ autopilot: false,
538
+ sources: sources.map(([source, n]) => ({
539
+ source,
540
+ documentIds: Array.from({ length: n }, (_, i) => `${source}-${i + 1}`),
541
+ total: n,
542
+ })),
543
+ waiting: 0,
544
+ ...over,
545
+ };
546
+ }
547
+ const CATEGORIES = [
548
+ { key: 'thin-content', label: 'Thin content', count: 9 },
549
+ { key: 'missing-meta-description', label: 'Missing meta description', count: 5 },
550
+ { key: 'meta-description-length', label: 'Meta description too long', count: 2 },
551
+ { key: 'meta-title-length', label: 'Meta title too long', count: 1 },
552
+ ];
553
+ describe('SEO scan results: Fix with AI', () => {
554
+ async function openResults(role = 'ADMIN') {
555
+ render(_jsx(Jobs, { onNavigate: () => { }, role: role, userId: "u1", config: CONFIG }));
556
+ await screen.findByRole('list', { name: 'Jobs' });
557
+ const row = document.getElementById('job-open-job_scan');
558
+ row.focus();
559
+ fireEvent.click(row);
560
+ const drawer = await screen.findByRole('dialog');
561
+ fireEvent.click(within(drawer).getByRole('tab', { name: /^Results/ }));
562
+ await within(drawer).findByText('Site score');
563
+ return drawer;
564
+ }
565
+ async function box(drawer) {
566
+ const text = await within(drawer).findByText(/Start a batch job/);
567
+ return text.closest('div').parentElement;
568
+ }
569
+ it('offers a batch job for the largest kind of issue a batch can fix, after the digest line', async () => {
570
+ server.jobs = [scan(CATEGORIES)];
571
+ server.targets = [
572
+ target('missing-meta-description', [['pages', 5]]),
573
+ target('meta-description-length', [['pages', 2]]),
574
+ ];
575
+ const drawer = await openResults();
576
+ const fix = await box(drawer);
577
+ expect(within(fix).getByText('Fix with AI')).toBeTruthy();
578
+ expect(fix.textContent).toContain('Start a batch job for the 5 missing meta descriptions. You’ll review each one before it’s applied.');
579
+ const digest = within(drawer).getByText(/SEO digest: Sent to 3 people/);
580
+ expect(digest.compareDocumentPosition(fix) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
581
+ const setUp = within(fix).getByRole('button', { name: 'Set up batch job' });
582
+ setUp.focus();
583
+ fireEvent.click(setUp);
584
+ const dialog = wizard();
585
+ expect(checkedOperation(dialog)).toBe('meta');
586
+ await toStep2(dialog, 'pages');
587
+ expect(within(dialog).getByText('5 selected')).toBeTruthy();
588
+ expect(estimateQuery()).toMatchObject({
589
+ operation: 'meta',
590
+ source: 'pages',
591
+ statusFilter: 'all',
592
+ documentIds: 'pages-1,pages-2,pages-3,pages-4,pages-5',
593
+ });
594
+ await queue(dialog, 5);
595
+ // The scan's drawer closes too; the new job is the list's top row, with focus.
596
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
597
+ expect(toast).toHaveBeenCalledWith('“Rewrite meta descriptions” queued · 5 documents');
598
+ const rows = [...document.querySelectorAll('[data-job-open]')];
599
+ expect(rows[0].id).toBe('job-open-job_new');
600
+ await waitFor(() => expect(document.activeElement).toBe(rows[0]));
601
+ });
602
+ it('returns focus to Set up batch job when the wizard closes, even after a click that didn’t focus it', async () => {
603
+ server.jobs = [scan(CATEGORIES)];
604
+ server.targets = [target('missing-meta-description', [['pages', 5]])];
605
+ const drawer = await openResults();
606
+ const setUp = within(await box(drawer)).getByRole('button', { name: 'Set up batch job' });
607
+ // Safari doesn't focus a clicked button, and neither does fireEvent.
608
+ expect(document.activeElement).not.toBe(setUp);
609
+ fireEvent.click(setUp);
610
+ fireEvent.keyDown(wizard(), { key: 'Escape' });
611
+ await waitFor(() => expect(document.querySelector('[data-batch-wizard]')).toBeNull());
612
+ expect(screen.getByRole('dialog')).toBe(drawer);
613
+ await waitFor(() => expect(document.activeElement).toBe(setUp));
614
+ });
615
+ it('skips a type SEO autopilot fixes on its own', async () => {
616
+ server.jobs = [scan(CATEGORIES)];
617
+ server.targets = [
618
+ target('missing-meta-description', [], { autopilot: true }),
619
+ target('meta-description-length', [['posts', 2]]),
620
+ ];
621
+ const drawer = await openResults();
622
+ const fix = await box(drawer);
623
+ expect(fix.textContent).toContain('Start a batch job to shorten the 2 meta descriptions that are too long. You’ll review each one before it’s applied.');
624
+ fireEvent.click(within(fix).getByRole('button', { name: 'Set up batch job' }));
625
+ const dialog = wizard();
626
+ expect(checkedOperation(dialog)).toBe('meta');
627
+ await toStep2(dialog, 'posts');
628
+ expect(estimateQuery()).toMatchObject({ operation: 'meta', source: 'posts' });
629
+ });
630
+ it('opens the wizard on Shorten long titles for SEO titles that are too long', async () => {
631
+ server.jobs = [scan(CATEGORIES)];
632
+ server.targets = [
633
+ target('missing-meta-description', [], { autopilot: true }),
634
+ target('meta-description-length', []),
635
+ target('meta-title-length', [['posts', 2]]),
636
+ ];
637
+ const drawer = await openResults();
638
+ const fix = await box(drawer);
639
+ expect(fix.textContent).toContain('Start a batch job to shorten the 2 SEO titles that are too long. You’ll review each one before it’s applied.');
640
+ fireEvent.click(within(fix).getByRole('button', { name: 'Set up batch job' }));
641
+ const dialog = wizard();
642
+ expect(checkedOperation(dialog)).toBe('titles');
643
+ await toStep2(dialog, 'posts');
644
+ expect(within(dialog).getByText('2 selected')).toBeTruthy();
645
+ expect(estimateQuery()).toMatchObject({
646
+ operation: 'titles',
647
+ source: 'posts',
648
+ documentIds: 'posts-1,posts-2',
649
+ });
650
+ });
651
+ it('names each content type when the documents span several, with a button for each', async () => {
652
+ server.jobs = [scan(CATEGORIES)];
653
+ server.targets = [
654
+ target('missing-meta-description', [
655
+ ['pages', 3],
656
+ ['posts', 2],
657
+ ]),
658
+ ];
659
+ const drawer = await openResults();
660
+ const fix = await box(drawer);
661
+ expect(fix.textContent).toContain('Start a batch job for the 5 missing meta descriptions: 3 in Pages and 2 in Posts. A batch runs on one content type, so there’s one to set up for each.');
662
+ expect(within(fix)
663
+ .getAllByRole('button')
664
+ .map((b) => b.textContent)).toEqual(['Set up batch job for Pages', 'Set up batch job for Posts']);
665
+ fireEvent.click(within(fix).getByRole('button', { name: 'Set up batch job for Posts' }));
666
+ await toStep2(wizard(), 'posts');
667
+ expect(within(wizard()).getByText('2 selected')).toBeTruthy();
668
+ });
669
+ it('shows no box when nothing is left to fix, or the documents can’t be read', async () => {
670
+ server.jobs = [scan(CATEGORIES)];
671
+ server.targets = [
672
+ target('missing-meta-description', [], { autopilot: true }),
673
+ target('meta-description-length', [], { waiting: 2 }),
674
+ ];
675
+ const drawer = await openResults();
676
+ await waitFor(() => expect(server.calls.some((c) => c.endpoint === '/seo/issues/batch-targets')).toBe(true));
677
+ await new Promise((resolve) => setTimeout(resolve, 0));
678
+ expect(within(drawer).queryByText('Fix with AI')).toBeNull();
679
+ cleanup();
680
+ server.targets = null;
681
+ server.calls = [];
682
+ const again = await openResults();
683
+ await waitFor(() => expect(server.calls.some((c) => c.endpoint === '/seo/issues/batch-targets')).toBe(true));
684
+ await new Promise((resolve) => setTimeout(resolve, 0));
685
+ expect(within(again).queryByText('Fix with AI')).toBeNull();
686
+ });
687
+ it('isn’t offered to viewers, who can’t queue jobs', async () => {
688
+ server.jobs = [scan(CATEGORIES)];
689
+ server.targets = [target('missing-meta-description', [['pages', 5]])];
690
+ const drawer = await openResults('VIEWER');
691
+ expect(within(drawer).getByText(/SEO digest/)).toBeTruthy();
692
+ expect(within(drawer).queryByText('Fix with AI')).toBeNull();
693
+ expect(server.calls.some((c) => c.endpoint === '/seo/issues/batch-targets')).toBe(false);
694
+ });
695
+ });
696
+ describe('a link to a job', () => {
697
+ it('opens the job’s drawer from /jobs?job=<id>', async () => {
698
+ server.jobs = [scan(CATEGORIES)];
699
+ render(_jsx(Jobs, { onNavigate: () => { }, currentPath: "/jobs?job=job_scan", role: "ADMIN", userId: "u1", config: CONFIG }));
700
+ const drawer = await screen.findByRole('dialog');
701
+ expect(within(drawer).getByRole('heading', { name: /SEO scan/ })).toBeTruthy();
702
+ });
703
+ it('ignores a job that isn’t in the list', async () => {
704
+ server.jobs = [scan(CATEGORIES)];
705
+ render(_jsx(Jobs, { onNavigate: () => { }, currentPath: "/jobs?job=job_gone", role: "ADMIN" }));
706
+ await screen.findByRole('list', { name: 'Jobs' });
707
+ expect(document.getElementById('job-open-job_scan')).toBeTruthy();
708
+ expect(screen.queryByRole('dialog')).toBeNull();
709
+ });
710
+ });
711
+ //# sourceMappingURL=run-with-ai.render.test.js.map